package com.huatek.busi.service.impl.pointtable;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.alibaba.dubbo.config.annotation.Service;
import com.google.common.collect.Maps;
import com.huatek.busi.common.PointTableMonitorTypeCode;
import com.huatek.busi.service.pointtable.PointTableEtlFactoryService;
import com.huatek.busi.service.pointtable.PointTableEtlService;
import com.huatek.torch.frame.exception.OwlException;
import com.huatek.torch.sql.beans.Pojo;

import lombok.extern.slf4j.Slf4j;

/**
 * PointTableEtlFactoryService实现类
 * 
 * @author edward
 * @Date 2019年8月22日
 */
@Slf4j
@Component
@Service(interfaceClass = PointTableEtlFactoryService.class)
public class PointTableEtlFactoryServiceImpl<T extends Pojo>
    implements ApplicationContextAware, PointTableEtlFactoryService {
    /** 实现类Map缓存 */
    private final Map<String, PointTableEtlService> serviceImplMap = Maps.newConcurrentMap();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, PointTableEtlService> beansOfTypeMap =
            applicationContext.getBeansOfType(PointTableEtlService.class);
        if (CollectionUtils.isEmpty(beansOfTypeMap)) {
            log.debug("implement class is empty!");
            return;
        }
        for (PointTableEtlService service : beansOfTypeMap.values()) {
            if (service.persistentClass() == null) {
                log.debug("{}.persistentClass is empty!", service.getClass().getName());
                continue;
            }
            serviceImplMap.put(service.persistentClass().getName(), service);
        }
    }

    private final PointTableEtlService serviceImpl(Map<String, Object> params) {
        String code = (String)params.get("pointTableMonitorTypeCode");
        PointTableMonitorTypeCode pointTableMonitorTypeCode = PointTableMonitorTypeCode.from(code);
        String key = pointTableMonitorTypeCode.getTableClass().getName();
        PointTableEtlService service = serviceImplMap.get(key);
        if (service == null) {
            throw new OwlException("找不到实现类：" + key);
        }
        return service;
    }

    @Override
    public Map<String, Object> findPointTablePageData(Map<String, Object> params) {
        return serviceImpl(params).findPointTablePageData(params);
    }

    @Override
    public Map<String, Object> exportPointTableData(Map<String, Object> params) {
        return serviceImpl(params).exportPointTableData(params);
    }
}
