package com.yihu.hos.listeners;

import com.yihu.hos.common.constants.ContextAttributes;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.interceptor.LocalContext;
import com.yihu.hos.services.ServiceFlowEventService;
import com.yihu.hos.web.framework.model.bo.ServiceFlow;
import com.yihu.hos.system.service.FlowManager;
import com.yihu.hos.web.framework.constant.DateConvert;
import com.yihu.hos.tenant.model.TenantModel;
import com.yihu.hos.tenant.service.TenantService;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Date;
import java.util.List;

/**
 * 项目启动执行
 * add by hzp at 2016-01-25
 */
public class ApplicationStart implements ServletContextListener {
    static private final Logger logger = LoggerFactory.getLogger(ApplicationStart.class);

    @Value("${hos.administrators}")
    private String saasAdmin;

    @Resource(name = TenantService.BEAN_ID)
    private TenantService tenantService;

    @Autowired
    private ServiceFlowEventService serviceFlowEventService;
    @Autowired
    private FlowManager flowManager;


    @Override
    public void contextInitialized(ServletContextEvent context) {
        //切换到主库
        try {
            TenantModel tenantModel = tenantService.findTenantByName(saasAdmin);
            if (tenantModel!=null){
                LocalContext.getContext().setAttachment(ContextAttributes.SCHEMA, tenantModel.getSchema());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        //使用自定义转化器转化时间格式
        ConvertUtils.register(new DateConvert(), Date.class);
        this.serviceFlowStarted();
    }

    @Override
    public void contextDestroyed(ServletContextEvent context) {
    }

    /**
     * admin启动时，触发一次所有流程更新事件，用于重启整个服务的情况。
     * 同时解决Broker中启动多个采集任务的问题。
     */
    private void serviceFlowStarted() {
        try {
            List<ServiceFlow> serviceFlowList = flowManager.getServiceFlowList();
            serviceFlowList.forEach(serviceFlow -> serviceFlowEventService.serviceFlowStarted(serviceFlow));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
