import {ApiCall} from "tsrpc";
import {ShopFun} from '../../public/shop';
import {ReqOpen, ResOpen} from "../../shared/protocols/shop/PtlOpen";
import {PublicShared} from '../../shared/public/public';

export default async function (call: ApiCall<ReqOpen, ResOpen>) {
    let shopId = call.req.shopId;
    let shopConf = G.gc.shop[shopId];

    if (!shopConf) {
        return call.error(globalThis.lng.shop_1);
    }

    if (!checkIsOpen(call, shopId)) {
        return call.error(globalThis.lng.shop_5);
    }

    let uid = shopId != "2" ? call.uid : call.conn.gud.ghId

    let shopData = await ShopFun.getShopData(uid, shopId, call.conn.gud.lv)

    call.succ(shopData);
}

function checkIsOpen(call: ApiCall, shopId: string | number) {
    let openCond = G.gc.shop[shopId].openCond;

    for (let i = 0; i < openCond.length; i++) {
        if (i % 2 != 0) continue;
        let k = openCond[i];
        let v = openCond[i + 1] as number;

        if (k == 'lv' && call.conn.gud.lv < v) return false;
        else if (k == 'day' && PublicShared.getOpenServerDay() < v) return false;
    }

    return true;
}