import ClassName from "../container/ClassName"
import { Injectable } from "../container/Injectable"
import IFeature from "../man/IFeature"
import TornStyleBlock from "../class/utils/TornStyleBlock"
import ADD_BEER_HEAD_HTML from "../../static/html/buyBeer/add_beer_head.html"
import SHOP_BEER_STATIC_ITEM_HTML from "../../static/html/buyBeer/shop_beer_static_item.html"
import globVars from "../globVars"
import Logger from "../class/Logger";
import BuyBeerHelper from "./BuyBeerHelper";

@ClassName('BeerShopModifier')
@Injectable()
export default class BeerShopModifier implements IFeature {
    private readonly logger = Logger.factory(BeerShopModifier)

    constructor(
        private readonly buyBeerHelper: BuyBeerHelper,
    ) {
    }

    description(): string {
        return "啤酒店页面修改";
    }

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

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

    urlIncludes(): RegExp[] {
        return [/shops.php\?step=bitsnbobs/];
    }

    start() {
        let block = new TornStyleBlock('啤酒助手').insert2Dom();
        block.setContent(ADD_BEER_HEAD_HTML);
        const msg_node = block.querySelector('#wh-msg');
        // 加入啤酒
        block.querySelector('button').addEventListener('click', e => {
            let node = document.querySelector('ul.items-list');
            if (!node) {
                msg_node.innerHTML = '❌ 商品未加载完';
                this.logger.error('商品未加载完');
                return;
            }
            if (node.querySelector('span[id="180-name"]')) {
                msg_node.innerHTML = '❌ 页面已经有啤酒了';
                this.logger.warn('商店页面已有啤酒');
                return;
            }
            const clear_node = node.querySelector('li.clear');
            const beer = document.createElement('li');
            beer.classList.add('torn-divider', 'divider-vertical');
            beer.style.backgroundColor = '#c8c8c8';
            beer.innerHTML = SHOP_BEER_STATIC_ITEM_HTML;
            if (clear_node) clear_node.before(beer);
            else node.append(beer);
            (<HTMLInputElement>e.target).disabled = true;
            msg_node.innerHTML = '添加成功';
        });

        // 监听啤酒购买
        globVars.responseHandlers.push((...args: any[]) => this.buyBeerHelper.responseHandler.apply(this.buyBeerHelper, args));
    }
}
