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

const ROOT_TAG = 'dblp';
const TAGS = [];

const parser = class Parser {

    constructor(path) {
        this._group = [];
        this._data = [];
        this._tagOk = false;
        this._isAuth = false;
        this.callback = null;
        this.result = {};
        this.from(path);
        this.dest = null;
        this.sax = require('sax').createStream(true);
        this.sax.on('error', this._error);
        this.sax.on('opentag', this._opentag);
        this.sax.on('closetag', this._closetag);
        this.sax.on('text', this._text);
    }

    parse(callback = null) {
        this.callback = callback;
        file.fs.createReadStream(this.source).pipe(this.sax);
    }

    from(source) {
        if (!file.exist(source)) {
            throw 'File not found';
        }
        let split = source.split('/');
        split = split[split.length - 1].split('.');
        if (split[split.length - 1] !== 'xml') {
            throw 'File is not an XML';
        }
        this.source = source;
    }

    to(dest) {
        if (!file.makedir(dest, true)) {
            throw 'Unable to create destination folder';
        }
        this.dest = dest;
        return this;
    }

    write() {
        if (this.dest === null) {
            throw 'No destination file';   
        }
    }

    _error(err) {
        throw err;
    }

    _opentag(node) {
        if (!this._tagOk && TAGS.indexOf(node.name) !== -1) {
            this._tagOk = true;
            this._group = [];
        } else if (!this._isAuth && node.name === 'author') {
            this._isAuth = true;
        } 
    }

    _closetag(tag) {
        if (tag === ROOT_TAG && this.callback !== null) {
            this._finish();
            if (this.callback !== null) {
                this.callback();
            }
        } else if (this._tagOk && TAGS.indexOf(tag) !== -1) {
            this._tagOk = false;
            this._data.push(this._group);
        } else if (this._isAuth && tag === 'author') {
            this._isAuth = false;
        }
    }

    _text(text) {
        if (this._isAuth) {
            this._group.push(text);
        }
    }
    
    _finish() {
        console.log(this._data);   
    }

};

module.exports = parser;
