import { outputSignal, errorSignal } from '#editor/editor'
import { Compiler } from '#compiler/compiler'
import { errorMessage, log } from '#utils/utils'
import { bytecodeToString } from 'reefvm'
import { parser } from '#parser/shrimp'
import { sendToNose } from '#editor/noseClient'
import { treeToString } from '#utils/tree'

export const runCode = async (input: string) => {
  try {
    const compiler = new Compiler(input)
    sendToNose(compiler.bytecode)
  } catch (error) {
    log.error(error)
    errorSignal.emit(`${errorMessage(error)}`)
  }
}

export const printParserOutput = (input: string) => {
  try {
    const cst = parser.parse(input)
    const string = treeToString(cst, input)
    outputSignal.emit(string)
  } catch (error) {
    log.error(error)
    errorSignal.emit(`${errorMessage(error)}`)
  }
}

export const printBytecodeOutput = (input: string) => {
  try {
    const compiler = new Compiler(input)
    outputSignal.emit(bytecodeToString(compiler.bytecode))
  } catch (error) {
    log.error(error)
    errorSignal.emit(`${errorMessage(error)}`)
  }
}
