import { _decorator, Component, find, Node } from 'cc';
import * as cc from 'cc';
const { ccclass, property } = _decorator;

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

    protected onLoad(): void {
        let sp = this.node.getChildByName("sp");
        let a = this.node.getChildByName("a");
        let b = this.node.getChildByName("b");
        
        let tt = sp.getComponent(cc.Sprite).spriteFrame;
        let x=168, y=250, width=84, height=50;
        // tt.rect = new cc.Rect(x, y - Math.round(Math.random()*100), width, height);
        tt.rect = new cc.Rect(x, y, width, height);
        // let vv = cc.Texture2D.WrapMode.CLAMP_TO_EDGE;
        // let vv = cc.Texture2D.WrapMode.REPEAT;
        // tt.texture.setWrapMode(vv, vv, vv);
        console.log(tt.texture)


        let content = find('Canvas/ScrollView/view/content/Node');
        for(var i = 0; i < 40; i++){
            for(var j = 0; j < 200; j++){
                var node = new cc.Node();
                var Sprite = node.addComponent(cc.Sprite);
                var wh = node.getComponent(cc.UITransform);
                wh.anchorX = 0;
                wh.anchorY = 1;
                wh.width = width
                wh.height = height;
                Sprite.spriteFrame = tt;

                if(j%2 == 0){
                    node.setPosition(i*width, -j*height/2)
                }else{
                    node.setPosition(i*width + width/2, -Math.floor(j/2)*height -height/2)
                }
                content.addChild(node);
            }
        }

        a.on(cc.Node.EventType.TOUCH_END, ()=>{
            for(var i = 0; i < content.children.length; i++){
                var node = content.children[i];
                var Sprite = node.getComponent(cc.Sprite);
                Sprite.spriteFrame = null;
            }
        }, this)
        b.on(cc.Node.EventType.TOUCH_END, ()=>{
            let arr:cc.Node[] = [];
            for(var i = 0; i < content.children.length; i++){
                var node = content.children[i];
                arr.push(node);
            }
            content.removeAllChildren();
            this.shuffle(arr)
            for(var i = 0; i < arr.length; i++){
                var node = arr[i];
                var Sprite = node.getComponent(cc.Sprite);
                Sprite.spriteFrame = tt;
                content.addChild(node);
            }
        }, this)
    }

    public shuffle(arr:any[], deep:number = 5){
        function sortFun(a,b){
            return Math.random() < .5 ? 1 : -1;
        }
        while(deep >0)  {
            arr.sort(sortFun);
            deep --;
        }
        return arr;
    }

    start() {

    }

    update(deltaTime: number) {
        
    }
}


