import CommonUtils from "../class/utils/CommonUtils";
import FetchUtils from "../class/utils/FetchUtils";
import InfoUtils from "../class/utils/InfoUtils";
import TRAVEL_STATE from "../enum/TravelState";
import LocalConfigWrapper from "../class/LocalConfigWrapper";
import { Injectable } from "../container/Injectable";
import ClassName from "../container/ClassName";
import Logger from "../class/Logger";
import MsgWrapper from "../class/utils/MsgWrapper";
import IFeature from "../man/IFeature";
import ATK_PAGE_REG from "./url/ATK_PAGE_REG";
import ALL_PAGE_REG from "./url/ALL_PAGE_REG";

/**
 * 公司助手
 */
@Injectable()
@ClassName('CompanyHelper')
export default class CompanyHelper implements IFeature {
    private readonly logger: Logger = Logger.factory(CompanyHelper)

    description(): string {
        return "公司助手、火车爆仓检测";
    }

    iStart(): void | Promise<void> {
        this.init()
    }

    urlExcludes(): RegExp[] {
        return [ATK_PAGE_REG];
    }

    urlIncludes(): RegExp[] {
        return [ALL_PAGE_REG];
    }

    public constructor(
        private readonly localConfigWrapper: LocalConfigWrapper,
        private readonly commonUtils: CommonUtils,
        private readonly fetchUtils: FetchUtils,
        private readonly infoUtils: InfoUtils,
        private readonly msgWrapper: MsgWrapper,
    ) {
    }

    init(): void {
        this.localConfigWrapper.config.CHTrainsDetectSwitch && this.trainsDetect().then();
    }

    /**
     * 火车检测
     * 每日判断一次，非公司老板跳过检测
     * TODO 优化、URL判断
     */
    private async trainsDetect(test: boolean = false): Promise<null> {
        // 通过用户的icon判断公司老板
        if ((await this.infoUtils.getSessionData()).statusIcons.icons.company.iconID !== 'icon73') {
            this.logger.info('火车检测跳过：非公司老板');
            return;
        }
        // 上次检测时间戳
        let lastDetect: number = this.localConfigWrapper.config.CHTrainsDetect || 0;
        // 检测是否过了一天
        if (test || this.commonUtils.isNewDay(lastDetect, -6)) {
            let travelStage = this.commonUtils.getTravelStage(),
                userStatus = (await this.infoUtils.getUserState()).status;
            test && this.logger.info({ travelStage, userStatus });
            if (travelStage === TRAVEL_STATE.IN_TORN && userStatus === 'ok')
                this.fetchUtils.fetchText('/companies.php')
                    .then(res => {
                        let tmp: HTMLElement = document.createElement('div');
                        let bodyTagStart = this.commonUtils.matchOne(res, /<body.+/);
                        if (!bodyTagStart) {
                            this.logger.warn('火车检测: 无法获取数据');
                            throw new Error('火车检测: 无法获取数据');
                        }
                        tmp.innerHTML = res.split(bodyTagStart)[1].split('</body>')[0].trim()
                            .replaceAll('rel="stylesheet"', '')
                            .replaceAll('.css', '?404')
                            .replaceAll('type="text/javascript"', 'type="application/json"');
                        let trainsNode = tmp.querySelector('span.trains');
                        if (!trainsNode) {
                            this.logger.error('火车检测出错: 无法获取火车数');
                            throw new Error('火车检测出错: 无法获取火车数');
                        }
                        let trains: number = parseInt(trainsNode.innerText);
                        let stars: number = tmp.querySelectorAll('.company-rating .active').length / 2 || 1;
                        // WuhuConfig.set('CHTrainsDetect', Date.now());
                        this.localConfigWrapper.config.CHTrainsDetect = Date.now();
                        this.logger.info('火车检测: 火车/星级: ' + trains + '/' + stars);
                        this.logger.info({ tmp });
                        if (trains + stars > 20) {
                            this.msgWrapper.create(`【公司助手】火车检测：火车明日将溢出！${ trains }/20火车`, {
                                timeout: 15,
                                force: true,
                                sysNotify: true
                            });
                        }
                        tmp.remove();
                        tmp = null;
                    })
                    .catch(error => {
                        this.logger.error('火车检测出错', error);
                    });
            else this.logger.warn('[火车检测] 用户状态错误，跳过火车检测', { travelStage, userStatus });
        } else {
            this.logger.info('火车检测：今日已提醒，跳过');
        }
    }
}
