package com.ruoyi.web.core.config;

import com.ruoyi.cc.domain.CcExtNum;
import com.ruoyi.cc.domain.CcParams;
import com.ruoyi.cc.service.ICcExtNumService;
import com.ruoyi.cc.service.ICcParamsService;
import com.ruoyi.cc.utils.MyFileUtil;
import com.ruoyi.common.utils.CommonUtils;
import com.ruoyi.common.utils.uuid.UuidGenerator;
import com.ruoyi.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.List;
import java.util.UUID;

@Slf4j
@Configuration
public class SysInitConfig implements ApplicationRunner {

    @Autowired
    private ICcExtNumService ccExtNumService;
    @Autowired
    private ICcParamsService ccParamsService;
    @Value("${sysconfig.init-reset-secret:false}")
    private Boolean initResetSecret;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (initResetSecret) {
            String lockerFile = getLockerFile();
            // run once on system first startup
            if (!new File(lockerFile).exists()) {
                log.info("=============reset loginTokenSecret and reset allExtensionsPassword when first startup============");
                resetLoginTokenSecret();
                resetAllExtensionsPassword();
                MyFileUtil.WriteStringToFile(lockerFile, "1");
            } else {
                log.info("==============file exists, not to reset============");
            }
        }
    }


    private String getLockerFile() {
        return String.format("%s%s",
                ccParamsService.getParamValueByCode("fs_conf_directory", "/home/freeswitch/etc/freeswitch"),
                "/autoload_configs/install_lock.data"
        );
    }

    private void resetAllExtensionsPassword(){
        List<CcExtNum> extNumList = ccExtNumService.selectCcExtNumList(new CcExtNum());
        for (CcExtNum ext : extNumList) {
            String uuid = UuidGenerator.GetOneUuid();
            String newPassword = CommonUtils.shuffleString(uuid);
            ext.setExtPass(newPassword);
            int affectRow = ccExtNumService.updateCcExtNum(ext);
            if(affectRow == 1){
                log.info("reset extension password successfully. extnum={}", ext.getExtNum());
            }else{
                log.info("Failed to reset extension password ! extnum={}", ext.getExtNum());
            }
        }
    }

    private void resetLoginTokenSecret() {
        log.info("try to resetLoginTokenSecret...");
        String newSecretKey = UUID.randomUUID().toString().replace("-", "").substring(0, 21);
        int affectRow = ccParamsService.updateParamsValue("ws-server-auth-token-secret", newSecretKey);
        if (1 == affectRow) {
            log.info("resetLoginTokenSecret finished successfully!");
        } else {
            log.info("Database Error! Failed to resetLoginTokenSecret!");
        }
    }
}
