import { _decorator, Component, Node } from 'cc';
import { SpriteFrame } from 'cc';
import { Sprite } from 'cc';
import { UITransform } from 'cc';
import { v3 } from 'cc';
import { size } from 'cc';
import GNode from '../GNode';
import { JNGSyncBase } from '../../../../components/JNComponent';
const { ccclass, property } = _decorator;

/**
 * 循环地图
 */

@ccclass('GMapLoop')
export class GMapLoop extends JNGSyncBase<{}> {

    map:SpriteFrame; //地图
    //地图重复次数
    repeat:number = 1;
    //一块的地图宽度
    mapWidth:number = 100;
    //一块的地图高度
    mapHeight:number = 100;

    //是否初始化
    isInit:boolean = false;
    //世界坐标Y轴
    worldY:number = 0;
    
    //创建的地图列表{开始区块:地图图片}
    createMaps:Map<number,Node> = new Map();
    

    init(map:SpriteFrame,repeat:number = 1,width:number = 0,height:number = 0){
        this.map = map;
        this.isInit = true;
        this.repeat = repeat;
        this.mapWidth = width || this.map.width;
        this.mapHeight = height || this.map.height;
        this.node.destroyAllChildren();
        this.createMaps = new Map;
    }

    //更新地图(世界坐标X)
    UpdateMap(x:number,offsetX:number = 0,offsetY:number = 0){

        //计算x在第几个区块
        let blockIndex = Math.floor((x + offsetX) / this.mapWidth);
        
        //生成区块的列表
        let maps:number[] = [];
        for (let index = 0; index < 1 + (this.repeat * 2); index++) {
            maps.push(blockIndex + (index - this.repeat));
        }

        //生成
        maps.forEach((blockIndex) => {
            this.createMap(blockIndex,offsetX,offsetY);
        })

        //销毁其他地图
        let keys = Array.from(this.createMaps.keys());
        keys.forEach(key => {
            if(maps.indexOf(key) < 0){
                this.createMaps.get(key).destroy();
                this.createMaps.delete(key);
            }
        })

    }

    //生成区块地图
    createMap(blockIndex:number,offsetX:number = 0,offsetY:number = 0){
        //计算区块开始位置
        let start = (blockIndex * this.mapWidth) - offsetX;

        if(!this.createMaps.get(blockIndex)){
            //生成地图
            let mapNode =  GNode.create();
            let uiTransform = mapNode.addComponent(UITransform);
            uiTransform.anchorX = 0;
            this.node.addChild(mapNode);
            mapNode.worldPosition = v3(start,offsetY,0)
            let mapImage = mapNode.addComponent(Sprite);
            mapImage.spriteFrame = this.map;
            mapImage.sizeMode = Sprite.SizeMode.CUSTOM;
            uiTransform.contentSize = size(this.mapWidth,this.mapHeight);
            this.createMaps.set(blockIndex,mapNode);
        }else{
            this.createMaps.get(blockIndex).worldPosition = v3(start,offsetY,0)
        }
    }
    
}


