import CommonUtils from "../class/utils/CommonUtils";
import UserScriptEngine from "../enum/UserScriptEngine";
import Popup from "../class/utils/Popup";
import STOCK_IMG_HTML from "../../static/html/stock_img.html";
import WindowActiveState from "../class/action/WindowActiveState";
import { Injectable } from "../container/Injectable";
import ClassName from "../container/ClassName";
import Logger from "../class/Logger";
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('TravelItem')
export default class TravelItem implements IFeature {
    private readonly logger: Logger = Logger.factory(TravelItem)

    description(): string {
        return "海外货物存量静默获取";
    }

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

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

    private readonly apiUrl: string = 'https://yata.yt/api/v1/travel/export/';
    private foreignStockInfo: any = null;

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

    public constructor(
        private readonly windowActiveState: WindowActiveState,
        private readonly commonUtils: CommonUtils,
    ) {
    }

    public init() {

        window.setInterval(async () => {
            if (!this.windowActiveState.get()) return;
            this.logger.info('COFetch ', this.apiUrl);
            try {
                this.foreignStockInfo = JSON.parse(await CommonUtils.COFetch(this.apiUrl));
            } catch (e) {
                this.logger.error('解析错误', e.stack || e.message || e);
            }
            this.logger.info({ info: 'TravelItem 跨域返回', 'returned': this.foreignStockInfo });
        }, 30 * 1000);
    }

    public get itemFiler() {
        return [
            {
                "name": "mex",
                "show": "墨西哥",
                "stocks": {
                    "Dahlia": "花",
                    "Jaguar Plushie": "偶"
                }
            },
            {
                "name": "cay",
                "show": "开曼",
                "stocks": {
                    "Banana Orchid": "花",
                    "Stingray Plushie": "偶"
                }
            },
            {
                "name": "can",
                "show": "加拿大",
                "stocks": {
                    "Crocus": "花",
                    "Wolverine Plushie": "偶"
                }
            },
            {
                "name": "haw",
                "show": "夏威夷",
                "stocks": {
                    "Orchid": "花",
                    "Large Suitcase": "大箱"
                }
            },
            {
                "name": "uni",
                "show": "嘤国",
                "stocks": {
                    "Heather": "花",
                    "Red Fox Plushie": "赤狐",
                    "Nessie Plushie": "水怪"
                }
            },
            {
                "name": "arg",
                "show": "阿根廷",
                "stocks": {
                    "Ceibo Flower": "花",
                    "Monkey Plushie": "偶",
                    "Tear Gas": "催泪弹"
                }
            },
            {
                "name": "swi",
                "show": "瑞士",
                "stocks": {
                    "Edelweiss": "花",
                    "Chamois Plushie": "偶"
                }
            },
            {
                "name": "jap",
                "show": "日本",
                "stocks": {
                    "Cherry Blossom": "花"
                }
            },
            {
                "name": "chi",
                "show": "祖国",
                "stocks": {
                    "Peony": "花",
                    "Panda Plushie": "偶"
                }
            },
            {
                "name": "uae",
                "show": "阿联酋 (UAE)",
                "stocks": {
                    "Tribulus Omanense": "花",
                    "Camel Plushie": "偶"
                }
            },
            {
                "name": "sou",
                "show": "南非",
                "stocks": {
                    "African Violet": "花",
                    "Lion Plushie": "偶",
                    "Xanax": "XAN"
                }
            }
        ]
    }

    // 呈现内容
    public async clickHandler(): Promise<void> {
        if (this.commonUtils.getScriptEngine() === UserScriptEngine.RAW) {
            new Popup(STOCK_IMG_HTML.replace('{{}}', performance.now().toString()), '飞花库存');
        } else {
            const popup = new Popup("请稍后 " + CommonUtils.loading_gif_html(), '飞花库存');
            let table = `<table><tr><th colspan="2">目的地 - 更新时间</th><th colspan="3">库存</th></tr>`;
            // const dest = FILTER.default;
            const dest = this.itemFiler;
            const now = new Date();
            const res = await this.get();
            this.logger.info({ res })
            if (!res || !res.stocks) return;
            dest.forEach(el => {
                const update = (now.getTime() - new Date(res.stocks[el.name]['update'] * 1000).getTime()) / 1000 | 0
                table += `<tr><td>${ el.show }</td><td>${ update / 60 | 0 }分${ update % 60 | 0 }秒前</td>`;
                let count = 0;
                res.stocks[el.name]['stocks'].forEach(stock => {
                    if (el.stocks[stock.name]) {
                        table += `<td${ stock['quantity'] === 0 ? ' style="background-color:#f44336;color:white;border-color:#000;"' : '' }>${ el.stocks[stock.name] } (${ stock['quantity'] })</td>`;
                        count++;
                    }
                });
                while (count < 3) {
                    count++;
                    table += '<td></td>';
                }
                table += '</tr>';
            });
            table += '</table>';
            popup.getElement().innerHTML = table;
        }
    }

    public async get() {
        try {
            return this.foreignStockInfo ||= JSON.parse(await CommonUtils.COFetch(this.apiUrl));
        } catch (e) {
            this.logger.error('解析出错', e.stack || e.message || e);
            return null;
        }
    }
}

// export const TravelItemKey = Symbol('TravelItemKey') as InjectionKey<TravelItem>
