const { LogType } = require("loguix")
const fs = require("fs")
const path = require("path")
const { __glob } = require("./global-variables")
const ulog = new LogType("Links")
const uuid = require("uuid")
const config = require("./config")
const {ApplyLinks} = require("../routes/link")



if(!fs.existsSync(__glob.DATA + path.sep + "links.json")) {
    fs.writeFileSync(__glob.DATA + path.sep + "links.json", JSON.stringify([], null, 2))
}

module.exports.getLinks = function() {
    return JSON.parse(fs.readFileSync(__glob.DATA + path.sep + "links.json"))
}

const FirstLinkManager = new ApplyLinks(this.getLinks())


module.exports.addLink = function(settings) {

    var canDo = true
    const links = this.getLinks()
    var id = makeid(8)

    if(settings.abstractLink) {
        settings.dest = id.toString()
    } 



    // Check if a destination already exists between links and if it's the case, we return an error "ALREADY_EXiST"
    links.forEach((link) => {
        if(link.dest == settings.dest) {

            canDo = false
        }

    })

    const link = {
        id: id,
        title: settings.title,
        url: settings.url,
        dest: settings.dest,
    }

    if(canDo) {

        links.push(link)
        fs.writeFileSync(__glob.DATA + path.sep + "links.json", JSON.stringify(links, null, 2))
        const LinkManager = new ApplyLinks(this.getLinks())
        return "OK"

    } else {

        return "ALREADY_EXIST"
    }


}

module.exports.removeLink = function(id) {
    const links = this.getLinks()
    const newLinks = []
    links.forEach((link) => {
        if(link.id != id) {
            newLinks.push(link)
        }
    })
    fs.writeFileSync(__glob.DATA + path.sep + "links.json", JSON.stringify(newLinks, null, 2))
    const LinkManager = new ApplyLinks(this.getLinks())
    return "OK"
}

module.exports.updateLink = function(id, settings) {
    const links = this.getLinks()
    const newLinks = []
    links.forEach((link) => {
        if(link.id == id) {
            link.title = settings.title
            link.url = settings.url
        }
        newLinks.push(link)
    })
    fs.writeFileSync(__glob.DATA + path.sep + "links.json", JSON.stringify(newLinks, null, 2))
    const LinkManager = new ApplyLinks(this.getLinks())
    return "OK"
}



function makeid(length) {
    let result = '';
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const charactersLength = characters.length;
    let counter = 0;
    while (counter < length) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
      counter += 1;
    }
    return result;
}
