package info.bukova.isspst.services.settings;

import info.bukova.isspst.data.Address;
import info.bukova.isspst.data.GlobalSettings;
import info.bukova.isspst.data.SettingsData;
import info.bukova.isspst.services.AbstractOwnedService;
import info.bukova.isspst.services.IsspstException;
import info.bukova.isspst.services.StringXmlMarshaller;

import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;

public class GlobalSettingServiceImpl extends AbstractOwnedService<GlobalSettings> implements
		GlobalSettingsService {
	
	private StringXmlMarshaller<SettingsData> marshaller;
	private SettingsData settings;
	
	public GlobalSettingServiceImpl(Marshaller marshaller, Unmarshaller unmarshaller) {
		this.marshaller = new StringXmlMarshaller<SettingsData>(marshaller, unmarshaller, SettingsData.class);
	}

	@Override
	@Transactional
	@PreAuthorize("hasPermission(this, 'PERM_ADD')")
	public void add(GlobalSettings entity) {
		if (!this.getAll().isEmpty()) {
			throw new IsspstException("Global settings allready exists");
		}
		
		if (entity.getData() == null || entity.getData().isEmpty()) {
			SettingsData data = new SettingsData();
			entity.setData(marshaller.marshalData(data));
		}
		
		super.add(entity);
	}

	@Override
	@Transactional
	public SettingsData getSettings() {
		if (settings == null) {
			GlobalSettings gs = this.getAll().get(0);
			settings = marshaller.unmarshalData(gs.getData());
		}
		return settings;
	}

	@Override
	@Transactional
	@PreAuthorize("hasPermission(this, 'PERM_EDIT')")
	public void updateSettings() {
		if (this.getAll().isEmpty()) {
			throw new IsspstException("Global settings does not exists");
		}
		
		GlobalSettings gs = this.getAll().get(0);
		
		for (Address a : settings.getShippingAddrs()) {
			a.setCompany(settings.getMainAddress().getCompany());
			a.setIc(settings.getMainAddress().getIc());
			a.setDic(settings.getMainAddress().getDic());
		}
		
		gs.setData(marshaller.marshalData(settings));
		
		super.update(gs);
	}
	
	
	
}
