const readline = require('readline');
const file = require('../../file');
const result = require('./result');

let instance = null;

const finder = class Finder {

    constructor() {
        this.result = [];
        this.name = '';
        this.source = null;
        this.callback = null;
        this.reader = null;
    }

    from(source) {
        if (!file.exist(source)) {
            throw 'Unable to find the source file';
        }
        this.source = source;
        return this;
    }

    find(name, callback = null) {
        if (this.source === null) {
            throw 'No source file';
        }
        this.callback = callback;
        this.name = name;
        this.reader = readline.createInterface({
            input: file.fs.createReadStream(this.source)
        });
        this.reader.on('line', this._line);
        this.reader.on('close', this._close);
    }

    _line(content) {
        const group = JSON.parse(content);
        if (group.indexOf(instance.name) !== -1) {
            instance.result.push(group);
        }
    }

    _close() {
        // Retire les doublons et l'auteur choisit
        let coauth = [];
        instance.result.forEach(group => {
            group.forEach(elt => {
                if (elt !== instance.name && coauth.indexOf(elt) === -1) {
                    coauth.push(elt);
                }
            });
        });
        // Retour
        let res = new result();
        res.name = instance.name;
        res.coAuthors = coauth;
        if (instance.callback !== null) {
            instance.callback(res);
        }
    }

};

module.exports.get = function () {
    if (instance === null) {
        instance = new finder();
    }
    return instance;
};
