package com.tzld.piaoquan.recommend.server.framework.recaller;


import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigObject;
import com.typesafe.config.ConfigValue;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**

 */

public class FilterConfig {
    private static Logger LOGGER = LoggerFactory.getLogger(FilterConfig.class);
    private List<FilterConfigInfo> filterConfigInfoList = new ArrayList<FilterConfigInfo>();

    public FilterConfig(Config config) {
        this.load(config);
    }


    public FilterConfig(String configFile) {
        this.load(configFile);
    }

    public FilterConfig() {
    }

    public boolean load(String configFile) {
        Config filterConfig = ConfigFactory.parseResources(configFile);
        return load(filterConfig);
    }

    public boolean load(Config config) {
        Config recallConfig = config.getConfig("recall-config");

        Config filterConf = recallConfig.getConfig("filter-config");
        try {
            loadFilters(filterConf);
        } catch (Exception e) {
            return false;
        }

        return true;
    }

    public List<FilterConfigInfo> getFilterConfigInfoList() {
        return filterConfigInfoList;
    }

    private void loadFilters(Config config) throws Exception {
        ConfigObject confObj = config.root();
        for (ConfigObject.Entry<String, ConfigValue> it : confObj.entrySet()) {
            Config conf = ((ConfigObject) it.getValue()).toConfig();

            // parse config
            String configName = it.getKey();
            String filterName = conf.getString("filter-name");
            int filterPriority = 0;
            if (conf.hasPath("filter-priority"))
                filterPriority = conf.getInt("filter-priority");

            List<Integer> disableExpIds = new ArrayList<Integer>();
            if (conf.hasPath("disable-expids")) {
                disableExpIds = conf.getIntList("disable-expids");
            }
            FilterConfigInfo filterConfigInfo = new FilterConfigInfo(configName,
                    filterName, filterPriority, disableExpIds);
            LOGGER.debug("parse filter config info [{}]", filterConfigInfo);

            addConfigByPriority(filterConfigInfoList, filterConfigInfo);
        }
    }

    private void addConfigByPriority(List<FilterConfigInfo> configInfoList, FilterConfigInfo addConfigInfo) {

        int pos = 0;
        for (; pos < configInfoList.size(); pos++) {
            if (configInfoList.get(pos).getFilterPriority() <= addConfigInfo.getFilterPriority()) {
                break;
            }
        }
        configInfoList.add(pos, addConfigInfo);
    }
}
