package com.utic.center.utic.traf.server.repository;

import com.utic.center.common.dto.ProcessStateDto;
import com.utic.center.utic.traf.server.dto.BatchJobInfoDto;
import com.utic.center.utic.traf.server.dto.TrafPrcsTimeDto;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Getter
public class ApplicationRepository {

    private ApplicationRepository() {
        throw new IllegalStateException("ApplicationRepository class");
    }

    public static final String TABLE_TRAFFIC_CENTER = "TRAFFIC_CENTER_";
    public static final String TABLE_TRAFFIC_CENTER_HIST = "TRAFFIC_CENTER_";

    public static boolean isLoadingLink = false;

    public static final ProcessStateDto processState = ProcessStateDto.builder()
            .processId("70030")
            .regDate("")
            .runState(ProcessStateDto.RUN_STATE.NORMAL.getValue())
            .rcvCnt(0)
            .sndCnt(0)
            .etcCnt(0)
            .errDesc("")
            .errTimeGap(120)
            .build();

    public static final TrafPrcsTimeDto trafPrcsTime = TrafPrcsTimeDto.builder()
            .currTime("")
            .prcsTime("")
            .past05MinTime("")
            .past10MinTime("")
            .incdTime("")
            .build();
    public static void setTrafPrcsTime(TrafPrcsTimeDto newPrcsTime) {
        trafPrcsTime.setCurrTime(newPrcsTime.getCurrTime());
        trafPrcsTime.setPrcsTime(newPrcsTime.getPrcsTime());
        trafPrcsTime.setPast05MinTime(newPrcsTime.getPast05MinTime());
        trafPrcsTime.setPast10MinTime(newPrcsTime.getPast10MinTime());
        trafPrcsTime.setIncdTime(newPrcsTime.getIncdTime());
    }

    public static int PRCS_THREAD_COUNT = 10;
    public static int DBMS_BATCH_SIZE = 2000;

    public static List<BatchJobInfoDto> batchJobInfoList = new ArrayList<>();

    public static void addJobInfo(BatchJobInfoDto jobInfo) {
        if (batchJobInfoList.size() > 72) {
            batchJobInfoList.remove(0);
        }
        batchJobInfoList.add(jobInfo);
    }

    private static String extractTargetTable(String ddlText) {
        if (ddlText == null || ddlText.isEmpty()) {
            return null;
        }
        // 정규식으로 FROM 절에서 테이블명 추출
        Pattern pattern = Pattern.compile("FROM\\s+(TRAFFIC_CENTER_[A-Z0-9_]+)", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(ddlText);
        if (matcher.find()) {
            return matcher.group(1).toUpperCase(); // 테이블명 반환
        }
        return null; // 매칭 실패
    }

    private static String getNextTargetTable(String currentTable) {
        if ("TRAFFIC_CENTER_A".equalsIgnoreCase(currentTable)) {
            return "TRAFFIC_CENTER_B";
        } else if ("TRAFFIC_CENTER_B".equalsIgnoreCase(currentTable)) {
            return "TRAFFIC_CENTER_A";
        } else {
            throw new IllegalArgumentException("알 수 없는 테이블명: " + currentTable);
        }
    }
    private static String getSuffix(String tableName) {
        int lastUnderscore = tableName.lastIndexOf('_');
        if (lastUnderscore != -1 && lastUnderscore < tableName.length() - 1) {
            return tableName.substring(lastUnderscore + 1);
        }
        return "A"; // 언더스코어가 없거나 잘못된 형식일 경우
    }

    public static String currTrafficCenter = "TRAFFIC_CENTER_A";
    public static String nextTrafficCenter = "TRAFFIC_CENTER_B";

    public static void setCurrentTrafficCenterView(String ddlText) {
        currTrafficCenter = extractTargetTable(ddlText);
        nextTrafficCenter = getNextTargetTable(currTrafficCenter);
        logActiveView();
    }
    public static String getCurrTrafficCenterSuffix() {
        return getSuffix(currTrafficCenter);
    }
    public static String getNextTrafficCenterSuffix() {
        return getSuffix(nextTrafficCenter);
    }
    public static void swapTrafficCenterView() {
        final String tmpTable = currTrafficCenter;
        currTrafficCenter = nextTrafficCenter;
        nextTrafficCenter = tmpTable;
        logActiveView();
    }

    private static void logActiveView() {
//        log.info("[INF] {}: Active-{}, Next-{}", LogUtils.elapsedLog("TRAFFIC_CENTER(VIEW)"), currTrafficCenter, nextTrafficCenter);
    }
}
