import fs from "fs";
// @ts-ignore
import solc from "solc"
import {logger} from "./logger";


export class ParseSol {
    file_path: string


    constructor(file_path: string) {
        this.file_path = file_path;
    }

    async parse() {
        logger.info(`movement compile solidity: ${this.file_path}`);
        const source = fs.readFileSync(this.file_path).toString()
        return new Promise((resolve, reject) => {
            solc.loadRemoteVersion("v0.8.7+commit.e28d00a7", (err: Error, solcSnapshot: any) => {
                if (err) {
                    logger.error("movement compile solidity err:", err)
                    throw reject(err)
                }
                const output = JSON.parse(solcSnapshot.compile(JSON.stringify({
                    language: "Solidity", sources: {
                        "demo.sol": {
                            content: source
                        }
                    }, "settings": {
                        "optimizer": {"enabled": true, "runs": 200},
                        "outputSelection": {
                            "*": {
                                "*": ["*"]
                            }
                        }
                    }
                })));
                // we can get bytecode and opcode from here, now we directly use the opcodes
                // @ts-ignore
                const contract = Object.values(output.contracts)[0].demo
                const abis = contract.abi.map((it: any) => {
                    it.opcodes = []
                    return it
                })
                const opcodesStr = contract.evm.deployedBytecode.opcodes;
                const opcodes = opcodesStr.split(" ")
                for (const opcode of opcodes) {
                    if (opcode === "ADD") {
                        abis[0].opcodes.push("ADD")
                        abis[0].opcodes.push("RETURN")
                        break
                    }
                }
                logger.success("movement parse solidity succeeded");
                resolve(abis)
            })
        })
        // return abis
    }

}
