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

import com.salesmanager.core.business.generic.exception.ServiceException;
import com.salesmanager.core.business.generic.service.SalesManagerEntityServiceImpl;
import com.salesmanager.core.business.system.dao.ModuleConfigurationDao;
import com.salesmanager.core.business.system.model.IntegrationModule;
import com.salesmanager.core.business.system.model.ModuleConfig;
import com.salesmanager.core.utils.reference.IntegrationModulesLoader;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.simple.JSONArray;
import org.json.simple.JSONValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

//TODO Jhonny cache removed
@Service("moduleConfigurationService")
public class ModuleConfigurationServiceImpl extends
        SalesManagerEntityServiceImpl<Long, IntegrationModule> implements
        ModuleConfigurationService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ModuleConfigurationServiceImpl.class);

    @Autowired
    private IntegrationModulesLoader integrationModulesLoader;


    private ModuleConfigurationDao integrationModuleDao;

//    @Autowired
//    private CacheUtils cache;

    @Autowired
    public ModuleConfigurationServiceImpl(
            ModuleConfigurationDao integrationModuleDao) {
        super(integrationModuleDao);
        this.integrationModuleDao = integrationModuleDao;
    }

    @Override
    public IntegrationModule getByCode(String moduleCode) {
        return integrationModuleDao.getByCode(moduleCode);
    }


    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public List<IntegrationModule> getIntegrationModules(String module) {


        List<IntegrationModule> modules = null;
        try {

            //CacheUtils cacheUtils = CacheUtils.getInstance();
//			modules = (List<IntegrationModule>) cache.getFromCache("INTEGRATION_M)" + module);
            if (modules == null) {
                modules = integrationModuleDao.getModulesConfiguration(module);
                //set json objects
                for (IntegrationModule mod : modules) {

                    String regions = mod.getRegions();
                    if (regions != null) {
                        Object objRegions = JSONValue.parse(regions);
                        JSONArray arrayRegions = (JSONArray) objRegions;
                        Iterator i = arrayRegions.iterator();
                        while (i.hasNext()) {
                            mod.getRegionsSet().add((String) i.next());
                        }
                    }


                    String details = mod.getConfigDetails();
                    if (details != null) {

                        //Map objects = mapper.readValue(config, Map.class);

                        Map<String, String> objDetails = (Map<String, String>) JSONValue.parse(details);
                        mod.setDetails(objDetails);


                    }


                    String configs = mod.getConfiguration();
                    if (configs != null) {

                        //Map objects = mapper.readValue(config, Map.class);

                        Object objConfigs = JSONValue.parse(configs);
                        JSONArray arrayConfigs = (JSONArray) objConfigs;

                        Map<String, ModuleConfig> moduleConfigs = new HashMap<String, ModuleConfig>();

                        Iterator i = arrayConfigs.iterator();
                        while (i.hasNext()) {

                            Map values = (Map) i.next();
                            String env = (String) values.get("env");
                            ModuleConfig config = new ModuleConfig();
                            config.setScheme((String) values.get("scheme"));
                            config.setHost((String) values.get("host"));
                            config.setPort((String) values.get("port"));
                            config.setUri((String) values.get("uri"));
                            config.setEnv((String) values.get("env"));
                            if ((String) values.get("config1") != null) {
                                config.setConfig1((String) values.get("config1"));
                            }
                            if ((String) values.get("config2") != null) {
                                config.setConfig1((String) values.get("config2"));
                            }

                            moduleConfigs.put(env, config);


                        }

                        mod.setModuleConfigs(moduleConfigs);


                    }


                }
//				cache.putInCache(modules, "INTEGRATION_M)" + module);
            }

        } catch (Exception e) {
            LOGGER.error("getIntegrationModules()", e);
        }
        return modules;


    }

    @Override
    public void createOrUpdateModule(String json) throws ServiceException {

        ObjectMapper mapper = new ObjectMapper();

        try {


            @SuppressWarnings("rawtypes")
            Map[] objects = mapper.readValue(json, Map[].class);


            //get the module to be loaded
            for (int i = 0; i < objects.length; i++) {
                @SuppressWarnings("rawtypes")
                Map o = objects[i];
                //get module object
                IntegrationModule module = integrationModulesLoader.loadModule(o);

                if (module != null) {
                    IntegrationModule m = this.getByCode(module.getCode());
                    if (m != null) {
                        this.delete(m);
                    }
                    this.create(module);
                }

            }


        } catch (Exception e) {
            throw new ServiceException(e);
        }


    }


}
