import toThousands from "../utils/toThousands";
import Log from "../../class/Log";
import Alert from "../../class/utils/Alert";
import LocalConfigWrapper from "../../class/LocalConfigWrapper";
import { Container } from "../../container/Container";

// 价格监视handle
export default function priceWatcherHandle(isPDA: boolean, PDA_APIKey: string) {
    let localConfigWrapper: LocalConfigWrapper = Container.factory(LocalConfigWrapper);

    let priceTemp = {};
    let intervalId = window.setInterval(() => {
        const price_conf = localConfigWrapper.config.priceWatcher;
        const apikey = isPDA ? PDA_APIKey : localStorage.getItem('APIKey');
        if (!apikey || (price_conf['pt'] === -1 && price_conf['xan'] === -1)) {
            Log.warn('价格监视关闭，无apikey或设置未打开');
            window.clearInterval(intervalId);
            return;
        }
        if (price_conf['pt'] !== -1) priceWatcherPt(apikey, price_conf['pt'], priceTemp).then();
        if (price_conf['xan'] !== -1) priceWatcherXan(apikey, price_conf['xan'], priceTemp).then();
    }, 10000)
}

// pt价格监视
async function priceWatcherPt(apikey, lower_price, priceWatcher) {
    Log.info('pt价格监视开始', { apikey: typeof apikey, lower_price, priceWatcher });
    if (!priceWatcher['watch-pt-lower-id']) priceWatcher['watch-pt-lower-id'] = [];
    const res = await window.fetch('https://api.torn.com/market/?selections=pointsmarket&key=' + apikey);
    const obj = await res.json();
    if (obj['pointsmarket']) {
        // 过滤低于价格的物品出售id
        const lower_arr = [];
        let low = Infinity;
        Object.keys(obj['pointsmarket']).forEach(key => {
            if (obj['pointsmarket'][key]['cost'] <= lower_price) {
                lower_arr.push(key);
                if (obj['pointsmarket'][key]['cost'] < low) low = obj['pointsmarket'][key]['cost'];
            }
        });
        if (lower_arr.length === 0) return;
        // 将id与之前存在的比较，不相同时发送通知
        if (JSON.stringify(priceWatcher['watch-pt-lower-id']) !== JSON.stringify(lower_arr)) {
            priceWatcher['watch-pt-lower-id'] = lower_arr;
            new Alert(`PT新低价：$${ toThousands(low) }( < $${ toThousands(lower_price) }) - <a href="/pmarket.php" target="_blank">点击转跳</a>`, {
                timeout: 6,
                sysNotify: true,
                sysNotifyClick: () => window.open('https://www.torn.com/pmarket.php'),
            });
        }
    } else {
        // 查询出错了
        Log.error('pt查询出错了')
    }
}

// xan价格监视
async function priceWatcherXan(apikey, lower_price, priceWatcher) {
    // 初始化记录上一个条目的id，避免重复发送通知
    if (!priceWatcher['watch-xan-lower-id']) priceWatcher['watch-xan-lower-id'] = '';
    const res = await window.fetch('https://api.torn.com/market/206?selections=bazaar&key=' + apikey);
    const obj = await res.json();
    if (obj['bazaar']) {
        const lowest_item = obj['bazaar'][0]
        if (lowest_item['cost'] <= lower_price) {
            if (priceWatcher['watch-xan-lower-id'] !== lowest_item['ID']) {
                priceWatcher['watch-xan-lower-id'] = lowest_item['ID'];
                new Alert(`XAN新低价：$${ toThousands(lowest_item['cost']) }( < $${ toThousands(lower_price) }) - <a href="/imarket.php#/p=shop&step=shop&type=&searchname=Xanax" target="_blank">点击转跳</a>`, {
                    timeout: 6,
                    sysNotify: true,
                    sysNotifyClick: () => window.open('https://www.torn.com/imarket.php#/p=shop&step=shop&type=&searchname=Xanax')
                });
            }
        }
    } else {
        // 查询出错了
        Log.error('xan查询出错了')
    }
}