package com.ag.demo;

import cn.hutool.core.collection.CollUtil;
import com.ag.base.DefaultBussniessImpl;
import com.ag.demo.entity.DbErrInfo;
import com.ag.util.StrUtil;
import com.ag.util.UUIDUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

@Service
public class DbErrInfoService {
    @Autowired
    private DefaultBussniessImpl bizDao;

    public void execute(org.json.JSONObject orgJson, HttpServletResponse response, HttpServletRequest request) throws IOException {
        List<String> data = getDataFromTxt();
        data.removeIf(info -> !info.trim().startsWith("ORA-"));
        List<DbErrInfo> dbs = CollUtil.list(false);
        for (String info : data){
            if (StrUtil.isEmpty(info)){
                continue;
            }
            String[] arr = info.split(":");
            if (arr.length != 2){
                continue;
            }
            DbErrInfo db = new DbErrInfo();
            db.setId(UUIDUtil.getUUID());
            db.setErrKey(arr[0]);
            db.setErrVal(arr[1]);
            dbs.add(db);
        }
        //System.out.println(JSON.toJSONString(dbs));
        bizDao.saveAll(dbs);
    }

    public List<String> getDataFromTxt() throws IOException {
        List<String> list = new ArrayList<>();
        BufferedReader br = null;
        try {
            File file = new File("f:\\tmp\\ora.txt");
            br = new BufferedReader(new InputStreamReader(Files.newInputStream(file.toPath()), "UTF-8"));
            String line;
            while (null != (line=br.readLine())) {
                list.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                br.close();
            }
        }
        return list;
    }
}
