import i18n from "../../../../i18n/i18n";
import Main from "../../../../main/Main";
import { __GodCard, __GodCardLevel } from "../../../data/sdata/SManage";
import { GodCardAttr } from "../../../data/udata/Player";

const {ccclass, property} = cc._decorator;

@ccclass
export default class CardItem extends cc.Component {

    @property(cc.Label)
    mName: cc.Label = null;

    @property(cc.Sprite)
    mIcon: cc.Sprite = null;

    @property(cc.Node)
    mStarNode: cc.Node = null;

    @property([cc.SpriteFrame])
    mStarFrame: Array<cc.SpriteFrame> = [];

    @property(cc.Node)
    mNoNode: cc.Node = null;

    @property(cc.Label)
    mCount: cc.Label = null;


    public main:Main
    public godCardAttr:GodCardAttr;
    public _godCard:__GodCard

    private callback:(cardItem:CardItem)=>void

    public init(main:Main,godCardAttr:GodCardAttr):number{
        if(this.mNoNode){
            this.mNoNode.active = false
        }
        this.node.zIndex = 1
        this.main = main
        this.godCardAttr = godCardAttr
        this._godCard = this.main.sManage.getGodCardById(godCardAttr.id)
        this.initIcon()
        return this.flushStar()
    }

    public initNo(main:Main,_godCard:__GodCard){
        this.main = main
        this._godCard = _godCard
        if(this.mNoNode){
            this.mNoNode.active = true
        }
        this.initIcon()
        let myCount = this.main.player.getGoodCount(this._godCard.goodId)
        this.mCount.string = myCount +'/'+this._godCard.goodCount
        if(myCount >= this._godCard.goodCount){
            this.node.zIndex = 0
        }else{
            this.node.zIndex = 2
        }
    }

    private initIcon(){
        if(this.mName){
            this.mName.string = i18n.t(this._godCard.name)
        }
        cc.resources.load('icon/card/'+this._godCard.id, cc.SpriteFrame, (err, spriteFrame:cc.SpriteFrame) =>{
            if(err){
                cc.error(err);
            }else{
               this.mIcon.spriteFrame = spriteFrame;
            }
        } );
    }

    public flushStar():number{
        let star = 5;
        if(this.godCardAttr.level < this._godCard.list.length){
            let _godCardLevel:__GodCardLevel = this._godCard.list[this.godCardAttr.level]
            star = _godCardLevel.star
        }
        
        let nodes = this.mStarNode.children
        for (let i = 0; i < nodes.length; i++) {
            const node = nodes[i];
            let sprite = node.getComponent(cc.Sprite)
            if(i < star){
                sprite.spriteFrame = this.mStarFrame[1]
            }else{
                sprite.spriteFrame = this.mStarFrame[0]
            }
        }
        return star
    }


    public setCallback(callback:(cardItem:CardItem)=>void){
        this.callback = callback
    }
    public onclick(){
        if(this.callback){
            this.callback(this)
        }
    }


}
