// Expirements - Search engine
var fs = require('fs')
var Fuse = require('fuse.js')
var path = require('path')
var express = require('express')

var app = express()
app.use('/', express.static('./public'))

function search(text) {
    var dbf = fs.readFileSync("search.csv").toString().trim().split("\n").map((ogstr) => {
        return ogstr.trim().split(',')
    }).map((lis) => {
        return {"url":lis[0], "title":lis[1], "desc":lis[2], "language":lis[3]}
    })

    var fuse = new Fuse(dbf, {"keys":['title', 'desc']})
    var fuse_search = fuse.search(text)

    return fuse_search
}

app.get('/', (req, res) => {
    var query = req.query.q
    if (query) {
        var srch = search(query)
        var table = []
        srch.forEach((fentry) => {
            var entry = fentry.item
            table.push(`<tr><td><a href="${entry.url}">${entry.title}</a></td><td>${entry.desc}</td></tr>`)
        })
        res.send(fs.readFileSync("./templates/search.html").toString().replace(";table", table.join("\n")))
    } else {
        res.sendFile(path.join(__dirname, "./templates/home.html"))
    }
})

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});
// All code originaly made by sapbot