package com.caliverse.admin.domain.service;

import com.caliverse.admin.domain.entity.HISTORYTYPE;
import com.caliverse.admin.domain.entity.Log;
import com.caliverse.admin.domain.dao.admin.HistoryMapper;
import com.caliverse.admin.domain.response.HistoryResponse;
import com.caliverse.admin.global.common.code.CommonCode;
import com.caliverse.admin.global.common.utils.CommonUtils;

import io.jsonwebtoken.io.IOException;
import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
@RequiredArgsConstructor
@Slf4j
public class HistoryService {

    private final HistoryMapper historyMapper;

    public HistoryResponse getHistoryList(Map requestParams){

        //페이징 처리
        requestParams = CommonUtils.pageSetting(requestParams);

        List<Log> historyList = historyMapper.getHistoryList(requestParams);

        int allCnt = historyMapper.getAllCnt(requestParams);

        return HistoryResponse.builder()
                .resultData(HistoryResponse.ResultData.builder()
                        .total(historyMapper.getTotal())
                        .totalAll(allCnt)
                        .pageNo(requestParams.get("page_no")!=null?
                                Integer.valueOf(requestParams.get("page_no").toString()):1)
                        .list(historyList).build())
                .status(CommonCode.SUCCESS.getHttpStatus())
                .result(CommonCode.SUCCESS.getResult())
                .build();
    }
    public HistoryResponse getHistoryDetail(String id){
        String logJson = historyMapper.getLogJson(id);
        return HistoryResponse.builder()
                .resultData(HistoryResponse.ResultData.builder().content(logJson).build())
                .status(CommonCode.SUCCESS.getHttpStatus())
                .result(CommonCode.SUCCESS.getResult())
                .build();
    }


   
    private void insertMetaData(File file) {
        try {
            // Read the JSON data from the file
            String jsonData = FileUtils.readFileToString(file, StandardCharsets.UTF_8);

            // Parse the JSON data into a JSONArray
            JSONArray jsonArray = new JSONArray(jsonData);

            
            // Iterate over the elements in the JSONArray
            for (int i = 0; i < jsonArray.length(); i++) {
                // Get the current element as a JSONObject
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                // Extract the values from the JSONObject
                Integer itemId = Integer.valueOf(jsonObject.getInt("item_id"));


                Map<String, Object> item = new HashMap<>();
                item.put("fileName", file.getName());
                item.put("dataId", itemId);
                item.put("jsonData", jsonObject.toString());


                // Insert the values into MariaDB
                
                historyMapper.insertMetaData(item);


                
            }
        } catch (java.io.IOException e) {
            log.error("insertMetaData IOException: {}", e.getMessage());
        } catch (JSONException e) {
            log.error("insertMetaData JSONException: {}", e.getMessage());
        }
    }

    public void setLog(HISTORYTYPE type, JSONObject content){
        //로그 기록
        Map<String, Object> logMap = new HashMap<>();
        logMap.put("adminId",  CommonUtils.getAdmin().getId());
        logMap.put("name",  CommonUtils.getAdmin().getName());
        logMap.put("mail",  CommonUtils.getAdmin().getEmail());
        logMap.put("type", type);
        logMap.put("content",content.toString());
        historyMapper.saveLog(logMap);
    }

    public void setScheduleLog(HISTORYTYPE type, String message){
        //스케줄 로그 기록
        Map<String, Object> logMap = new HashMap<>();
        logMap.put("adminId",  1);
        logMap.put("name",  "schedule");
        logMap.put("mail",  "schedule");
        logMap.put("type", type);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message",message);
        logMap.put("content",jsonObject.toString());
        historyMapper.saveLog(logMap);
    }
}
