package org.well.well.resp;

import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.well.well.base.AbstractResponse;
import org.well.well.base.DeviceTypeEnum;
import org.well.well.manager.DeviceConfigManager;
import org.well.well.manager.H2SManager;
import org.well.well.manager.ImeiManager;

public class H2SResponse extends AbstractResponse {

    private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    private static final String[] mType = {"Data", "Event", "SetResponse", "GetResponse", "StartupRequest"};

    @Override
    public void run() {
        ClassPathXmlApplicationContext ac = this.getAc();
        H2SManager h2SManager = ac.getBean(H2SManager.class);
        ImeiManager imeiManager = ac.getBean(ImeiManager.class);
        DeviceConfigManager deviceConfigManager = ac.getBean(DeviceConfigManager.class);
        JSONObject json = JSONObject.fromObject(this.getContent());
        String devCode = json.get("devCode").toString();
        logger.info("--------RECEIVE:设备编号：" + devCode + "，上传数据：" + json.toString() + "-------");
        JSONObject jsonObject = (JSONObject) json.get("mBody");
        if (mType[0].equals(json.get("mType"))) {//存储上报数据
            h2SManager.processNormalData(jsonObject, devCode);
        } else if (mType[1].equals(json.get("mType"))) {//存储报警事件
            h2SManager.processAlarmData(jsonObject, devCode);
        } else if (mType[2].equals(json.get("mType"))) {//三码存储
            try {
                if (DeviceTypeEnum.HydrogenSulfide.name().equals(json.get("devType"))) {
                    if ("HydrogenSulfideConfigSuccess".equals(jsonObject.get("bType"))) {
                        deviceConfigManager.updateStatus(devCode);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("--------ERROR:设备编号：" + devCode + "，更新参数下发状态失败-------");
            }
        }else if (mType[4].equals(json.get("mType"))) {//三码存储
            try {
                String imei = jsonObject.getString("imei");
                String iccid = jsonObject.getString("iccid");
                imeiManager.saveData(devCode,imei,iccid);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("--------ERROR:设备编号：" + devCode + "，更新参数下发状态失败-------");
            }
        }
    }
}