package com.tsi.api.server.service;

import com.tsi.api.server.error.TscSsipApiErrorCode;
import com.tsi.api.server.mybatis.TscSsipAppMapper;
import com.tsi.api.server.mybatis.TsiDatabaseMapper;
import com.tsi.api.server.mybatis.vo.AbstractDbmsVo;
import com.tsi.api.server.mybatis.vo.AlarmOccrVo;
import com.tsi.api.server.repository.TsiAlarmManager;
import com.tsi.api.server.vo.*;
import com.tsi.app.common.app.AppUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

@Slf4j
@Service
@Transactional(rollbackFor = {Exception.class})
public class TscSsipAppService {

    private final TscSsipAppMapper tscNaviApiMapper;
    private final TsiDatabaseMapper tsiDatabaseMapper;

    public TscSsipAppService(TsiDatabaseMapper tsiDatabaseMapper) {
        this.tsiDatabaseMapper = tsiDatabaseMapper;
        this.tscNaviApiMapper = (TscSsipAppMapper) AppUtils.getBean(TscSsipAppMapper.class);
    }

    @Transactional(readOnly = true)
    public List<NodeStatusVo> getNodeStatusList() {
        return tscNaviApiMapper.getNodeStatusList();
    }

    @Transactional(readOnly = true)
    public NaviAuthorizedVo getApiAuthorizedInfo(String apiId, String deviceId) {
        return tscNaviApiMapper.getDeviceAuthorizedInfo(apiId, deviceId);
    }

    public TscSsipApiErrorCode getAuthorizedInfo(String apiId, String deviceId, String remoteIP) {

        NaviAuthorizedVo authorized = getApiAuthorizedInfo(apiId, deviceId);
        if (authorized == null) {
            // 등록되지 않은 사용자
            return TscSsipApiErrorCode.UNREGISTERED_APITOKEN;
        }

        log.info("{}", authorized.toString());
        if (!authorized.getUseYn().equals("Y")) {
            // 사용하지 않음으로 등록되어 있는 경우. 현재 사용할 수 없습니다. 관리자에게 문의하십시요.
            return TscSsipApiErrorCode.NOT_AVAILABLE;
        }
        if (!authorized.getState().equals("C")) {
            // 최초 디바이스 등록후 관리자가 확인하여 등록하지 않은 상태
            return TscSsipApiErrorCode.PENDING_REGISTRATION;
        }
        if (!authorized.getExpired().equals("N")) {
            // 유효기간이 지남
            return TscSsipApiErrorCode.APITOKEN_EXPIRED;
        }
        return TscSsipApiErrorCode.SUCCESS;
    }

    public int registerDevice(DeviceInfo deviceInfo) {
        return tscNaviApiMapper.registerDevice(deviceInfo);
    }
    public List<VersionVo> getVersion() {
        return tscNaviApiMapper.getVersion();
    }
    public int insertInvokeHs(ApiInvokeVo invokeVo, boolean isAlarm) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+9"));
        invokeVo.setEventDt(sdf.format(date));
        if (isAlarm) {
            TsiAlarmConfigVo alarmConfig = TsiAlarmManager.getInstance().get(TsiAlarmConfigVo.API_01);
            if (alarmConfig != null) {
                AlarmOccrVo alarm = new AlarmOccrVo(AbstractDbmsVo.DBMS_ALARM_OCCR_HS);
                alarm.setAlarmCode(TsiAlarmConfigVo.API_01);
                alarm.setAlarmTarget(invokeVo.getApiId());
                alarm.setAlarmValue(invokeVo.getApiToken() + ", " + String.valueOf(invokeVo.getError()));
                tsiDatabaseMapper.insertAlarmOccrHs(alarm);
            }
        }
        return tscNaviApiMapper.insertInvokeHs(invokeVo);
    }

}
