package com.nokia.alarm.service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nokia.alarm.entity.ResultMap;
import com.nokia.alarm.util.ExportUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class AlarmSaveToGPandPGService {

    @Autowired
    private ApiCallService apiCallService;

    @Autowired
    private ResultMapService resultMapService;

    public void newAlarm(Date date) {
        long start = System.currentTimeMillis();
        // 获取新增告警
        List<ResultMap> results = apiCallService.getNewAlarm(date);
        // 使用gpload入库到GP数据库
        // 写入文件
        String dString = ExportUtil.saveToCsv(results);
        // gpload
        String gploadCommand = "sh /data1/s130/alarm/gpload/alarm.sh " + dString;
        log.info("新增告警goload:--{}", gploadCommand);
        try {
            int exitCode = Runtime.getRuntime().exec(gploadCommand).waitFor();
            log.info("新增告警gpload完成...{}, 耗时 {} 毫秒...", exitCode, System.currentTimeMillis() - start);
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
            log.error("新增告警gpload失败: {}", e.getMessage());
        }
        // 通过轮询批量插入PG数据库
        resultMapService.insertData(results);
        log.info("新增告警 {} 时间 入库PG完成, 耗时 {} 毫秒...", date, (System.currentTimeMillis() - start));
    }

    public void updateAlarm(Date date) {
        long start = System.currentTimeMillis();
        // 获取取消告警
        List<ResultMap> results = apiCallService.getCanceledAlarm(date);
        // 通过gpload入库到GP数据库
        // 写入文件
        String dString = ExportUtil.saveToCsv(results);
        // gpload
        String gploadCommand = "sh /data1/s130/alarm/gpload/alarm.sh " + dString;
        log.info("消除告警goload:--{}", gploadCommand);
        try {
            int exitCode = Runtime.getRuntime().exec(gploadCommand).waitFor();
            log.info("消除告警gpload完成。。。。。{}", exitCode);
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
            log.error("消除告警gpload失败: {}", e.getMessage());
        }
        // 通过resultMapService更新到PG数据库
        resultMapService.updateOrInsertData(results);
        log.info("消除告警 {} 时间 入库完成, 耗时 {} 毫秒...", date, (System.currentTimeMillis() - start));
    }
}
