package com.utic.center.utic.stat.server.service.partition;

import com.utic.center.utic.stat.server.dao.repository.dwdb.UticStatTableManagerRepository;
import com.utic.center.utic.stat.server.dto.TableInfoDto;
import com.utic.center.utic.stat.server.dto.TableExistDto;
import lombok.Getter;

import java.util.ArrayList;
import java.util.List;

@Getter
public class StatTable extends MakeTablePartition {

    private final List<TableInfoDto> statTables = new ArrayList<>();

    public StatTable(UticStatTableManagerRepository repo,
                     String crtMonth,
                     String commentCrtMonth) {
        super(repo, crtMonth, commentCrtMonth);

        this.statTables.add(new TableInfoDto("STAT_5MIN_CENTER", "5분통계-중앙센터"));
        this.statTables.add(new TableInfoDto("STAT_5MIN_LOC", "5분통계-지역센터"));
        this.statTables.add(new TableInfoDto("STAT_15MIN_CENTER", "15분통계-중앙센터"));
        this.statTables.add(new TableInfoDto("STAT_15MIN_LOC", "15분통계-지역센터"));
    }

    @Override
    public boolean createPartitionTable() {
        for (TableInfoDto table : this.statTables) {
            final String tableName = table.getTable() + "_" + this.crtMonth;
            final String tableComment = table.getDesc() + " " + this.commentCrtMonth;
            if (!createTable(tableName, tableComment)) {
                return false;
            }
        }
        return true;
    }

    private boolean createTable(String tableName, String tableComment) {
        TableExistDto existDto = this.repo.findTableExist(tableName);
        if (existDto == null) {
            return false;
        }
        if (existDto.getTableExist() > 0) {
            return true;
        }

        if (this.repo.createStatTable(tableName) < 0) {
            return false;
        }
        if (this.repo.addStatPrimaryKey(tableName) < 0) {
            return false;
        }
        addComments(tableName, tableComment);
        return true;
    }

    private void addComments(String tableName, String tableComment) {
        this.repo.addTableComment(tableName, tableComment);

        this.repo.addColumnComment(tableName, "stat_date", "통계일시");
        this.repo.addColumnComment(tableName, "linkid", "링크ID");
        this.repo.addColumnComment(tableName, "linklevel", "링크레벨");
        this.repo.addColumnComment(tableName, "day_type", "요일구분(1:일요일,2:월요일,3:화요일,4:수요일,5:목요일,6:금요일,7:토요일)");
        this.repo.addColumnComment(tableName, "speed", "평균속도");
        this.repo.addColumnComment(tableName, "travel_time", "여행시간");
        this.repo.addColumnComment(tableName, "data_cnt", "데이터갯수");
    }

}
