import { SELF_REGISTER_HANDLER_NAME } from '@coinweb/contract-kit';
import { selfRegisterHandler } from '@coinweb/self-register';
import { addMethodHandler, ContractHandlers, executeHandler, executor } from 'cwait';

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

import { addWord } from './addWord';
import { mutexLock } from './mutex/lock';
import { mutexUnlock, mutexUnlockExec } from './mutex/unlock';

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

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

  addMethodHandler(module, '_lock', mutexLock);
  addMethodHandler(module, '_unlock', mutexUnlock);
  addMethodHandler(module, '_unlock_exec', mutexUnlockExec);

  addMethodHandler(module, SELF_REGISTER_HANDLER_NAME, selfRegisterHandler);

  return module;
};

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

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