import { _decorator, Component, Node, MeshRenderer, instantiate } from 'cc';
import BasePanel from '../../../core/component/BasePanel';
import Data from '../../../core/manager/Data';
import levelsData from 'db://assets/data/levelsData';
import platformSystem from 'db://assets/platform/platformSystem';
import audioManager from 'db://assets/manager/audioManager';
import { constants } from 'db://assets/data/constants';
const { ccclass, property } = _decorator;

@ccclass('NewPackOpenedLayer')
export class NewPackOpenedLayer extends BasePanel {
    onBtnClicked(event: any, customEventData: any) {
        audioManager.playOneShot(constants.audios.btnclick);
        this.close();
    }
    show() {
        
        platformSystem.platform.showInterstitialAd();
        let node_items = this.GetGameObject("node_items");
        node_items.children.map(a => a.active = false);

        let ids = [];
        let OpenItems:Array<any> = levelsData.getNormModelDatas();
        for (var i = Data.user.openIndex; i < Data.user.openIndex + 8 && i < OpenItems.length; ++i) {
            ids.push(OpenItems[i]);
        }
        for (var i = 0; i < node_items.children.length; ++i) {
            let child = node_items.children[i];
            child.active = true;
            this.setMesh(child, ids[i]);
        }
        Data.user.openIndex += 8;
        Data.user.openIndex = Math.min(Data.user.openIndex, OpenItems.length - 1);
        Data.save();
    }

    private setMesh(node: Node, name: string) {
        levelsData.LoadItemPrefabByName(name).then((res: any) => {
            let tmp: Node = instantiate(res);
            let render = tmp.getComponentInChildren(MeshRenderer) as MeshRenderer;
            let mesh = render.mesh;
            node.scale = render.node.scale.multiplyScalar(100);
            node.getComponent(MeshRenderer).mesh = mesh;
            tmp.destroy();
        })
    }
}

