package com.salesmanager.core.business.services.system;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.salesmanager.core.business.constants.Constants;
import com.salesmanager.core.business.exception.ServiceException;
import com.salesmanager.core.business.modules.email.Email;
import com.salesmanager.core.business.modules.email.EmailConfig;
import com.salesmanager.core.business.modules.email.HtmlEmailSender;
import com.salesmanager.core.model.merchant.MerchantStore;
import com.salesmanager.core.model.system.MerchantConfiguration;

import br.ufrgs.inf.prosoft.cache.SingleCache;

@Service("emailService")
public class EmailServiceImpl implements EmailService {

	@Inject
	private MerchantConfigurationService merchantConfigurationService;
	
	@Inject
	private HtmlEmailSender sender;
	
	@Override
	public void sendHtmlEmail(MerchantStore store, Email email) throws ServiceException, Exception {

		EmailConfig emailConfig = getEmailConfiguration(store);
		
		sender.setEmailConfig(emailConfig);
		sender.send(email);
	}

public static SingleCache<MerchantStore, EmailConfig> getEmailConfigurationCache = new SingleCache<>("16#static-single:EmailServiceImpl.getEmailConfiguration");

	@Override
	public EmailConfig getEmailConfiguration(MerchantStore store) {

return getEmailConfigurationCache.computeIfAbsent(store,  () -> {
		
		EmailConfig emailConfig = null;
		try {
			MerchantConfiguration configuration = merchantConfigurationService.getMerchantConfiguration(Constants.EMAIL_CONFIG, store);
			if(configuration!=null) {
				String value = configuration.getValue();
				
				ObjectMapper mapper = new ObjectMapper();
				emailConfig = mapper.readValue(value, EmailConfig.class);
			}
		} catch(ServiceException ex) {
		} catch(Exception e) {
			// throw new ServiceException("Cannot parse json string " + value);
		}
		return emailConfig;
}, 1200000);
	}
	
	
	@Override
	public void saveEmailConfiguration(EmailConfig emailConfig, MerchantStore store) throws ServiceException {
		MerchantConfiguration configuration = merchantConfigurationService.getMerchantConfiguration(Constants.EMAIL_CONFIG, store);
		if(configuration==null) {
			configuration = new MerchantConfiguration();
			configuration.setMerchantStore(store);
			configuration.setKey(Constants.EMAIL_CONFIG);
		}
		
		String value = emailConfig.toJSONString();
		configuration.setValue(value);
		merchantConfigurationService.saveOrUpdate(configuration);
	}

}
