import { getSprNode } from "./util";
import BaseBgManager from "./BaseBgManager";

cc.Class({
  extends: BaseBgManager,
  properties: {
    bgArr: {
      default: [],
    },
    maxId: 5,
  },

  initAllBg() {
    for (let i = 0; i < 5; i++) {
      const bg = this.initOneBg(i + 1);
      this.bgArr.push(bg);
    }
  },

  initOneBg(id) {
    const bg = getSprNode("bg/" + id + "/bg_" + id);
    bg.scale = this._context.mapScaleMax;

    const bgItemLayer = new cc.Node();
    bgItemLayer.scale = 1 / bg.scale;
    bg.addChild(bgItemLayer);

    const itemTop = getSprNode("bg/" + id + "/bg_top" + id);
    bgItemLayer.addChild(itemTop, 1);
    this.toTop(itemTop);

    const itemBottom = getSprNode("bg/" + id + "/bg_bottom" + id);
    bgItemLayer.addChild(itemBottom, 1);
    this.toBottom(itemBottom);

    const item = getSprNode("bg/" + id + "/bg_dian" + id);
    bgItemLayer.addChild(item);
    item.x = (-this._context.bgWidth / 10) * 4;
    item.y = -this._context.bgHeight / 6;
    item.scale = this._context.mapScaleMin;

    if (id == 4) {
      itemTop.scale = this._context.mapScaleMin;

      const itemLeft = getSprNode("bg/" + id + "/bg_left");
      bgItemLayer.addChild(itemLeft);
      this.toLeft(itemLeft);

      const itemRight = getSprNode("bg/" + id + "/bg_right");
      bgItemLayer.addChild(itemRight);
      this.toRight(itemRight);
    }

    return bg;
  },

  getNext() {
    if (this.bgArr.length === 0) {
      this.initAllBg();
    }

    const newId = this._getBgNewId();
    const newBg = this.bgArr[newId-1];

    if (newBg.parent) {
      newBg.removeFromParent();
    }

    console.log('newId: ', newId);
    return newBg;
  },


  _curId: null,
  _getBgNewId() {
    if (!this._curId) {
      this._curId = Math.ceil( Math.random() * this.maxId );
    } else {

      const arr = Array.from(new Array(this.maxId+1).keys()).slice(-this.maxId);
      arr.splice(this._curId-1, 1);
      const index = Math.floor( Math.random() * arr.length );
      this._curId = arr[index];
    }

    return this._curId;
  },
});
