import { ctx } from "./config";

let initOrder = ["deviceCtrl", "natsCtrl", "recvCtrl", "msgCtrl"];
export async function SetInitOrder<K extends keyof typeof ctx>(ctrls: K[]) {
  initOrder = ctrls;
}

let OnReadyCtrls = Object.keys(ctx);
export async function SetOnReadyCtrls<K extends keyof typeof ctx>(ctrls: K[]) {
  OnReadyCtrls = ctrls;
}

let excludeCtrls = [] as string[];
export async function SetExcludeCtrls<K extends keyof typeof ctx>(ctrls: K[]) {
  excludeCtrls = ctrls;
}

export async function InitControllers() {
  console.log("begin init ");
  let n = initOrder.length;
  for (let i = 0; i < n; i++) {
    //@ts-ignore
    await ctx[initOrder[i]].onReady();
  }
  const keys = OnReadyCtrls.slice(0);
  while (n--) {
    if (initOrder.indexOf(keys[n]) != -1) {
      keys.splice(n, 1);
    }
  }

  if (excludeCtrls.length > 0) {
    n = keys.length;
    while (n--) {
      if (excludeCtrls.indexOf(keys[n]) != -1) {
        keys.splice(n, 1);
      }
    }
  }

  keys.forEach((k) => {
    //@ts-ignore
    ctx[k].onReady();
  });
  console.log("end init");
}

export function useCtx() {
  return ctx;
}
