const utils = require('../../dist/utils/utils.js').default // eslint-disable-line
const logger = require('../../dist/utils/logger.js').default // eslint-disable-line
const { doSearch } = require('../../dist/utils/classes.js') // eslint-disable-line
const { loadData } = require('../../dist/utils/actions.js') // eslint-disable-line
const fs = require('fs') // eslint-disable-line

const minpercent = 95
const logPath = './duplicateRemovingLog/'
const globalLog = './duplicateRemovingLog/log'
utils.CreatePath(logPath)
utils.WriteFile('', globalLog)

const params = process.argv.splice(2)
const path = params[0]
const question = params[1]
const answer = params[2]

// ---------------------------------------------------------------------------------
//
// ---------------------------------------------------------------------------------

console.time('SEARCH')
const searchRes = search({
    qdb: loadData(path),
    subjName: 'Elektronika',
    question: {
        Q: question,
        A: answer,
        data: {
            type: 'simple',
        },
    },
    searchTillMatchPercent: 80,
})
hr()
console.log('Search result')
hr()
showSearchResult(searchRes)
hr()
console.timeEnd('SEARCH')
log(
    `Searched for question: "${C('green')}${question}${C()}" answer: "${C(
        'green'
    )}${answer || ''}${C()}" in "${C('cyan')}${path}${C()}"`
)
hr()

// ---------------------------------------------------------------------------------
// logging and tools
// ---------------------------------------------------------------------------------

function showSearchResult(res) {
    res.forEach((x) => {
        console.log(`${C('green')}Q:${C()}`, x.q.Q)
        console.log(`${C('green')}A:${C()}`, x.q.A)
        console.log(`${C('green')}match:${C()}`, x.match)
        console.log()
    })
    console.log(`Result length: ${C('green')}${res.length}${C()}`)
}

function search({ qdb, subjName, question, searchInAllIfNoResult }) {
    return doSearch(
        qdb,
        subjName,
        question,
        null,
        minpercent,
        searchInAllIfNoResult
    )
}

function hr() {
    let res = ''
    for (let i = 0; i < process.stdout.columns; i++) {
        res += '='
    }
    log(`${C('cyan')}${res}${C()}`)
}

function log(text) {
    utils.AppendToFile(text, globalLog)
    if (process.stdout.isTTY) {
        process.stdout.clearLine()
        process.stdout.cursorTo(0)
    }

    console.log(text)
}

function C(color) {
    return logger.C(color)
}
