import { _decorator, BoxCollider2D, CircleCollider2D, Color, Component, director, instantiate, Material, Node, PolygonCollider2D, Prefab, Rect, RigidBody2D, Sprite, UIRenderer, UITransform, Vec4, view } from 'cc';
import { HoleAction } from './HoleAction';
import { PinAction } from './PinAction';
import { PoolMgr } from './PoolMagr';
import { ColorDate } from './ColorDate';
import { Global } from './Global';
import { events } from './Enums';
const { ccclass, property } = _decorator;

@ccclass('ElementAction')
export class ElementAction extends Component {
    // cur_color:ColorDate = null;
    start() {
    }

    update(deltaTime: number) {
        let currentPosition = this.node.getPosition()
        if (currentPosition.y < - view.getVisibleSize().height / 2) {
          this.node.removeFromParent();
          director.emit(events.remove_element,this);
        }
    }

    /**
     * X关 ，钉子总数  
     * @returns 
     */
    public get_hole_num(): number {
        let hole_num: number = 0;
        this.node.children.forEach(element => {
            if (element.getComponent(HoleAction)) {
                hole_num++;
            }
        });
        return hole_num;
    }


    public init_element(group_id: number, ele_color: ColorDate) {
        this.node.getComponent(RigidBody2D).group = group_id;
        this.node.getComponents(BoxCollider2D).forEach(element => {
            element.group = group_id;
        });
        this.node.getComponents(CircleCollider2D).forEach(element => {
            element.group = group_id;
        });
        this.node.getComponents(PolygonCollider2D).forEach(element => {
            element.group = group_id;
        });
        //set img color
        // this.cur_color = ele_color;
        this.node.children.forEach(element => {
            if (element.name == "img") {
                let img = element.getComponent(Sprite);
                img.color = new Color(ele_color.r, ele_color.g, ele_color.b, 190);
            }
        });
    }

    public init_pin(group_id: number, color_pin_arr: ColorDate[]) {
        //获取 hole
        this.node.children.forEach(element => {
            if (element.getComponent(HoleAction)) {      
                let new_pin = instantiate(PoolMgr.ins.getPrefab("pin"));
                this.node.addChild(new_pin);
                new_pin.setPosition(element.position);
                new_pin.getComponent(PinAction).init_date(group_id, color_pin_arr.shift());
            
            }
        });
    }

    get_pin_color(arr:PinAction[]){
        this.node.children.forEach(pin_node => {
            // pin_node.getComponent(PinAction)?.get_pin_color(arr);
            let pin_action = pin_node.getComponent(PinAction)
            if(pin_action&&pin_action.pin_color){  
                arr.push(pin_node.getComponent(PinAction));
            }
        });
    }

}

