let fs = require("fs")
let readFile = require('util').promisify(fs.readFile)
let { Compiler } = require('@asimovdev/asimovjs')
let { to } = require('await-to-js')
let Module = require('../lib/flow_4.0.1')
let compiler = new Compiler(Module)

async function loadSolFile(path) {
  try {
    const text = await readFile(path, 'utf-8')
    return text
  } catch (err) {
    throw err
  }
}

async function compileSolFile(path) {
  let sources = {};
  try {

    const text = await loadSolFile(path)
    sources[path] = { content: text }
    const [err, result] = await to(compiler.compile(sources))

    if (err) {
      throw err
    }

    let contracts = result.contracts[path]
    let errors = result.errors

    errors.forEach(e => {
      if (e.severity == 'error') {
        throw e.formattedMessage
      }
    });
    return contracts

  } catch (err) {
    throw err
  }

}

module.exports = {
  loadSolFile: loadSolFile,
  compileSolFile: compileSolFile
}
