import { _decorator, Component, Node, Prefab, CCObject, Vec3, instantiate} from "cc";
import { BulletCtrl } from "./BulletCtrl";
import { Config } from "../../IndependentScript/Config";
const { ccclass, property } = _decorator;

@ccclass("BulletManagerCtrl")
export class BulletManagerCtrl extends Component {

  private _isPause:boolean = false;
  public get isPause(){
    return this._isPause;
  }
  public set isPause(val:boolean){
    this._isPause = val;
    let childern = this.node.children;
    for(let i=0; i<childern.length; i++){
      let node:Node = childern[i] as Node;
      if(cc.isValid(node, true)){
        let bulletCtrl = node.getComponent(BulletCtrl);
        bulletCtrl.isPause = val;
      }
    }
  }

  @property({ type: Prefab })
  public bulletPrefab: Prefab = null;

  @property({ type: Node })
  public playerNode: Node = null;

  start() {

  }

  update(deltaTime: number) {
    if(this.isPause == true){
      return;
    }

    this.updateForBulletsPos(deltaTime);
    this.updateForBulletDistance(deltaTime);
  }

  // _updateForTest(dt:number){
  //   this.createBullet(cc.v3(0,0.8,0),  cc.v3(0,0,-1));
  // }

  createBullet(bulletIndex: number, bulletPos: Vec3, direct: Vec3) {
    let bullet: Node = instantiate(this.bulletPrefab);
    let bulletCtrl: BulletCtrl = bullet.getComponent(BulletCtrl);
    direct.normalize();
    bulletCtrl.setDirect(direct);
    bulletCtrl.setBornPos(bulletPos);
    bulletCtrl.init(Config.GunConfig[bulletIndex]);
    bullet.setParent(this.node as Node);
  }

  updateForBulletsPos(dt: number) {
    let children = this.node.children;
    for (let i = 0; i < children.length; i++) {
      let bullet = children[i];
      if (cc.isValid(bullet, true)) {
        let bulletCtrl: BulletCtrl = bullet.getComponent(BulletCtrl);
        let offset = cc.v3();
        Vec3.multiplyScalar(offset, bulletCtrl.direct, bulletCtrl.speed * dt);
        Vec3.add(offset, bullet.getPosition(), offset);
        bullet.setPosition(offset);
      }
    }
  }

  updateForBulletDistance(dt: number) {
    let children = this.node.children;
    for (let i = 0; i < children.length; i++) {
      let bullet = children[i];
      if (cc.isValid(bullet, true)) {
        let bulletCtrl: BulletCtrl = bullet.getComponent(BulletCtrl);
        let bornPos = bulletCtrl.bornPos;
        let curPos = bullet.getPosition();
        let distance = Vec3.distance(bornPos, curPos);
        if (distance > bulletCtrl.flightDistance) {
          bulletCtrl.boxCollider.off("onTriggerExit", bulletCtrl.onTriggerExit, bulletCtrl);
          bullet.destroy();
          cc.log("一颗子弹因为达到了自己的最大射程而死亡了");
        }
      }
    }
  }
}
