const fs = require('fs')
const path = require('path')

if (typeof (process.env.AUTOJS_NATIVE_LIBRARY_PATH) === 'undefined') {
    throw new Error('Not supported Auto.js Pro version. Sees https://g.pro.autojs.org/docs/v9 .')
}

const targetBinDir = path.join(process.env.AUTOJS_NATIVE_LIBRARY_PATH, 'opencv4autojs')
const package = require('../package.json')
const version = package.prebuiltVersion
const targetBinPath = path.join(targetBinDir, `${version}.${process.arch}.node`)

if (!fs.existsSync(targetBinPath)) {
    copyBin(targetBinDir, targetBinPath)
}

function copyBin(binDir, binPath) {
    if (fs.existsSync(binDir)) {
        fs.readdirSync(binDir).forEach(file => fs.unlinkSync(path.join(binDir, file)))
    } else {
        fs.mkdirSync(binDir, { recursive: true })
    }
    const sourceBinPath = path.join(__dirname, `../prebuilt/opencv4autojs.${process.arch}.node`)
    fs.copyFileSync(sourceBinPath, binPath)
}

module.exports = require(targetBinPath)