import { _decorator, Animation, Camera, color, Color, Component, EventTouch, find, geometry, instantiate, Layers, lerp, Material, MeshRenderer, Node, PhysicsSystem, Prefab, Rect, Sprite, tween, v3, Vec3 } from 'cc';
import { BlockMgr } from './BlockMgr';
import { BlockBase } from './BlockBase';
import { BlockArr, ColorConfig, emptyLineArr } from './Config';
const { ccclass, property } = _decorator;

@ccclass('main')
export class main extends Component {

    maxCol = 28;
    startX = -6.75;
    startY = -12;
    sub = 0.5;
    startLine = 41;

    bornPosi: Vec3 = v3(-0.25, 7, -30)
    rowIndex = 0;

    @property(Prefab)
    boomPrefa: Prefab = null;

    @property(Prefab)
    blockPrefab: Prefab = null;

    @property(Node)
    blocks: Node = null;

    @property(Node)
    touchNode: Node = null;

    @property(Camera)
    readonly cameraCom!: Camera;

    @property(Node)
    public targetNode!: Node;

    @property(Node)
    public previewBlocks:Node=null;

    @property(Material)
    blockMat: Material = null;

    public nowBlock: Node = null;
    public simpeDropBlocks: Node[] = [];
    public tempDropBlocks: Node[] = [];

    nowMapColorIndex = 0;

    nowColor;

    private _ray: geometry.Ray = new geometry.Ray();

    blockIndex = 0;

    start() {
        this.initLevel();
       
    
    }


    initLevel() {
        this.rowIndex = 1;
        this.nowColor = ColorConfig[this.nowMapColorIndex].clone();
        this.setBlockColor(this.nowColor)
        for (let i = 1; i < 44; i++) {
            this.productRowBlock();

        }
    }

    productRowBlock() {
        let emptyArr = emptyLineArr[this.rowIndex];
        for (let i = 1; i <= this.maxCol; i++) {
            if (emptyArr.indexOf(i) == -1) {
                //过滤空白的
                let block = instantiate(this.blockPrefab);
                let scale = 0.985;
                block.scale = v3(scale, scale, scale)
                block.parent = this.blocks;
                block.position = this.getPosi(this.rowIndex, i);
                block.addComponent(BlockBase).canDrop = false;
            }
        }
        this.rowIndex++;
    }

  

    setBlockColor(color:Color) {
        this.blockMat.setProperty('mainColor', color);
    }

   
    /**获取row  和col  对应的position */
    getPosi(row, col) {
        return v3(this.startX + (col - 1) * this.sub, this.startY + (this.startLine - row) * this.sub, -30)
    }

 
 

  
    findPosi(x, y) {
        for (let i = 0; i < this.blocks.children.length; i++) {
            let child = this.blocks.children[i];
            if (x == child.position.x && y == child.position.y) {
                return child;
            }
        }
        return null;
    }

  
    timer = 0;
    update(deltaTime: number) {
        this.blocks.setPosition(v3(this.blocks.position.x, this.blocks.position.y + 0.002));
      

        this.timer++;
        if (this.timer > 150) {
            this.timer = 0;
            this.productRowBlock();
        }

    }
}

