import { SELF_REGISTER_HANDLER_NAME, ContractHandlers as CKContractHandlers } from '@coinweb/contract-kit';
import { selfRegisterHandler } from '@coinweb/self-register';
import { addMethodHandler, ContractHandlers, executeHandler, executor, MethodCallback, selfCallWrapper } from 'cwait';
import { queue } from 'lib/onchain';

import { PUBLIC_METHODS } from '../offchain/shared';

import { addWord } from './addWord';

const addWrappers = (method: MethodCallback): MethodCallback => {
  return selfCallWrapper(method);
};

const createModule = (): ContractHandlers => {
  const module: ContractHandlers = { handlers: {} };

  addMethodHandler(module, PUBLIC_METHODS.ADD_WORD, addWrappers(executor(addWord)));

  addMethodHandler(module, SELF_REGISTER_HANDLER_NAME, selfRegisterHandler);

  queue.applyQueue(module as CKContractHandlers, [PUBLIC_METHODS.ADD_WORD]);

  return module;
};

export const cwebMain = () => {
  return (async () => {
    const module = createModule();

    await executeHandler(module);
  })();
};
