var {GameNotificationKey} = require('../utils/GameEnum');
var Item = require("UserInsertCardItem");
const GameModule = require('../utils/GameModule');

cc.Class({
    extends: cc.Component,

    properties: {
        cardLayout: cc.Layout,

        cardPrefab: cc.Prefab,

        cardsArray: [Item],
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        for (var i = 0; i < 3; i++) {
            let item = cc.instantiate(this.cardPrefab);
            item = item.getComponent('UserInsertCardItem');
            this.cardsArray.push(item);
            this.cardLayout.node.addChild(item.node);
        }

        let width = this.cardLayout.node._contentSize.width;
        let gap = (width - 3*190) / 2;
        this.cardLayout.spacingX = gap;

        this.setEventListener();
    },

    setEventListener() {
        GameEvent.on(GameNotificationKey.InsertCardToUser, this, (cardInfo) => {
            this.insertCardToUser(cardInfo);
        });

        GameModule.homeGuide.on('Fire_state32', this.openPack, this);
    },

    start () {
        GameModule.homeGuide.getComponent('HomeGuide').handleState('state32')
    },

    init(list, uid) {
        this.uid = uid;
        if (list != undefined) {
            this.list = list;
            for (var i = 0; i < list.length; i++) {
                let itemModel = list[i];
                let itemMng = this.cardsArray[i];
                itemMng.configCardInfo(itemModel, uid);
            }
        }
    },

    onDisable() {
      this.cardsArray.forEach(item => {
          if (item.isHasCard == true) {
              item.isHasCard = false;
          }
      });
    },

    // update (dt) {},
    closeAction() {
        this.node.active = false;
    },

    openPack() {
        GameEvent.fire(GameNotificationKey.OpenPack,false);
    },

    insertCardToUser(cardInfo) {
        for(var index in this.cardsArray) {
            let item = this.cardsArray[index];
            if (item.isHasCard == false) {
                item.configCardInfo(cardInfo,this.uid);
                break;
            }
        }
    },
});
