import { _decorator, Node, Sprite, SpriteFrame} from 'cc';
import { PoolManager } from '../core/manager/PoolManager';
import { Game } from './Game';
import { Constants } from '../data/Constants';
import { BaseExp } from '../core/base/BaseExp';
const { ccclass, property } = _decorator;

@ccclass('BulletMagazine')
export class BulletMagazine extends BaseExp {
    @property({type:Node,tooltip:"滚动内容"})
    public content: Node;
    @property({type:Node,tooltip:"子弹预制体"})
    public bullet: Node;
    @property({type:SpriteFrame,tooltip:"用过的子弹图片"})
    public use_sf: SpriteFrame;
    @property({type:SpriteFrame,tooltip:"正常的子弹图片"})
    public nor_sf: SpriteFrame;

    //当前子弹总数量
    private _magazineNum: number = 0;
    public set magazineNum(value: number) {
        this._magazineNum = value;
        this.loadMagazine()
    }
    public get magazineNum(): number {
        return this._magazineNum!;
    }
    //弹夹中的子弹图片节点
    public bullets: Node[] = [];

    start() {
        this.bullet.active = false;
        //更换弹夹
        this.register(Constants.eventName.magazine_num_change,this.loadMagazine.bind(this));
    }

    /**
     * 加载子弹 弹夹
     */
    public loadMagazine(){
        if(!Game.I.player.gun
           ||Game.I.isGameOver)return;
        this.recycle();
        const gData:any = Game.I.player.pData;
        let s_bullet: number = gData.magazine - Game.I.player.gun.shotBullets;
        for(let idx = 0; idx < this._magazineNum; idx++) {
            let n: Node = PoolManager.getNode(this.bullet,this.content);
            this.bullets.push(n);
            n.getChildByName("kd_sp").getComponent(Sprite).spriteFrame = idx < s_bullet ? this.nor_sf : this.use_sf;
        }
    }

    protected onDisable(): void {
        this.recycle();
    }

    public recycle(){
        this.bullets.forEach((item: Node) => {
            if(item.parent){
               PoolManager.putNode(item);
            }
        });
        this.bullets = [];
    }
}

