import { Node, Prefab, instantiate, resources } from "cc";
import { audioManager } from "./audioManager";
import { config } from "../config";
import { SdkUtil } from "../sdkUtil";

export class uiManager  {
    private static instance:uiManager =null;
    public static  Instance(){
        if(this.instance==null){
            this.instance = new uiManager
        }
        return this.instance
    }
    private ui_parent:Node = null
    private loading_view:Node = null
    private send_msg_view:Node = null
    public init(ui_node:Node,loading_node:Node,send_msg_loading:Node){
        this.ui_parent = ui_node
        this.send_msg_view = send_msg_loading
        this.loading_view = loading_node
    }

    public showUi(ui_path:string,parent:Node =null,cb=null){
        if(this.ui_parent==null){
            return console.error("ui_parent not init..")
        }
        resources.load(ui_path,Prefab,(err,fb:Prefab)=>{
            if(!err){
                let node = instantiate(fb)
                if(parent!=null){
                    node.parent = parent
                }else{
                    node.parent = this.ui_parent
                }
                if(cb!=null){
                    cb(node)
                }
            }else{
                console.error("showUi error:",err)
            }
        })
    }

    public showLoading(title:string='正在加载...'){
        if(this.loading_view!=null){
            SdkUtil.showLoading(title)
            this.loading_view.active = true
        }else{
            console.error("loading view not init..")
        }
    }

    public hideLoading(){
        if(this.loading_view!=null){
            SdkUtil.hideLoading()
            this.loading_view.active = false
        }else{
            console.error("loading view not init..")
        }
    }

    public static showToast(title:string,duration=2000,success_cb=null,fail_cb=null) {
        SdkUtil.showToast(title, duration,success_cb,fail_cb)
    }

    public static showModal(title:string, content:string, suc_cb=null, fail_cb=null, confirmText:string='确定', showCancel:boolean=true, cancelText:string='取消') {
        SdkUtil.showModal(title,content,suc_cb,fail_cb,confirmText,showCancel,cancelText)
    }

    public showSendMsgWait(){
        if(this.send_msg_view!=null){
            this.send_msg_view.active = true
        }else{
            console.error("send_msg_view view not init..")
        }
    }

    public hideSendMsgWait(){
        if(this.send_msg_view!=null){
            this.send_msg_view.active = false
        }else{
            console.error("send_msg_view view not init..")
        }
    }

    public onButtonListen(btn:Node,call_back){
        btn.on(Node.EventType.TOUCH_END,()=>{
            audioManager.Instance().playSound(config.AUDIO.btn)
            call_back()
        })
    }
}


