import { _decorator, Component, EditBox, Vec2, Node, Size } from 'cc';
import { tools } from '../../tools';
import { attributes_data } from '../../../data/data';
const { ccclass, property } = _decorator;

@ccclass('attributes_anchor')
export class attributes_anchor extends Component {
    @property(EditBox) editBox_x:EditBox = null;
    @property(EditBox) editBox_y:EditBox = null;
    @property(Node) btn_set:Node = null;
    private m_att_data: attributes_data = null;
    private call_back:Function = null;
    start() {
        this.editBox_x.node.on(EditBox.EventType.EDITING_DID_ENDED, ()=>{
            this.change()
        })
        this.editBox_y.node.on(EditBox.EventType.EDITING_DID_ENDED, ()=>{
            this.change()
        })
        this.btn_set.on(Node.EventType.TOUCH_END, ()=>{
            if(this.m_att_data.src.length==0) {
                return tools.showToast('还没有图片资源')
            }
            tools.loadUrl(this.m_att_data.src,null,(sf)=>{
                if(sf==null) {
                    return tools.showToast('图片资源加载失败')
                }
                let res_size = new Size(this.m_att_data.width, this.m_att_data.height)
                let res_anchor = new Vec2(this.m_att_data.anchor_x, this.m_att_data.anchor_y)
                tools.show_setup_res_anchor(sf,res_size,res_anchor,(v:Vec2)=>{
                    this.update_editStatus(v.x, v.y)
                    if(this.call_back!=null){
                        this.call_back(v)
                    }
                })
            })
        })
    }

    initView(call:Function){
        this.call_back = call
    }

    change(){
        if(this.call_back!=null){
            this.call_back(new Vec2(parseFloat(this.editBox_x.string),parseFloat(this.editBox_y.string)))
        }
    }

    update_att(att_data:attributes_data, x:number, y:number) {
        this.m_att_data = att_data
        this.update_editStatus(x,y)
    }

    update_editStatus(x:number, y:number) {
        if(x==undefined||x==null) {
            x = 0.5
        }
        if(y==undefined||y==null) {
            y = 0.5
        }
        this.editBox_x.string = x.toString()
        this.editBox_y.string = y.toString()
    }
}

