/**
 * 负责app之间的消息的接收模块
 */
import { nanoid } from "nanoid";
import { Controller } from "../core/controller";
import { useCtx } from "../ctx";

export type AssetSendedCallback = (assetUri:string)=>Promise<boolean>;
export type AssetType = "empty" | "webpackuri"
const RevcChangeEvent = "app.recv.change"
class AssetListener {
    id = "";
    type = "empty" as AssetType;
    constructor(public actionName:string, public callback: AssetSendedCallback){
        this.id = actionName;
    }
    
    toJson() {
        return {
            id: this.id,
            type: this.type,
            action: this.actionName,
        }
    }
}


export class AppMsgRecvController extends Controller {

    listeners = [] as AssetListener[];
    appGuid = "";

    async onReady() {
        const {deviceCtrl, natsCtrl} = useCtx();

        this.appGuid = deviceCtrl.profile.appGuid;

        natsCtrl.subscribe(`send.${this.appGuid}`, async (msg:{id:string,fromKey:string, uri:string,name?:string, thumbnail?:string})=>{
            const listen = this.listeners.find(item=>item.id == msg.id)
            if (!listen) return {
                isOk: false,
                error: "nolistener"
            }
            const ok = await listen.callback(msg.uri);
            return JSON.stringify({ isOk: ok})
        })

        natsCtrl.subscribe(`recv.actions.${this.appGuid}`, async ()=>{
            return JSON.stringify(this.listeners.map(item=>item.toJson()))
        })
    }


    //清除所有监听者
    clearListeners() {
        this.listeners = [];
    }

    emitChange() {
        const {natsCtrl} = useCtx();
        natsCtrl.publish(RevcChangeEvent, JSON.stringify({Guid: this.appGuid}))
    }

    //添加资源监听者  
    addAssetsListener(actionName:string, handle: AssetSendedCallback) {
        let listen = this.listeners.find(item=>item.actionName == actionName);
        if (listen)  {
            listen.callback = handle;
            return listen.id;
        }
        listen = new AssetListener(actionName, handle)
        listen.type = "webpackuri";
        this.listeners.push(listen);
    }

    removeListener(id:string) {
        let listen = this.listeners.find(item=>item.id == id);
        if (!listen)  {
            return;
        }
        this.listeners.splice(this.listeners.indexOf(listen), 1);
    }
}
