"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = __importDefault(require("fs"));
const readline_1 = __importDefault(require("readline"));
const neo4j = __importStar(require("neo4j-driver"));
const line$ = (path) => readline_1.default.createInterface({
    input: fs_1.default.createReadStream(path),
    crlfDelay: Infinity
});
const templateGTnode = (args) => {
    let tmp = 'CREATE (gt:GoTerm {';
    Object.keys(args).forEach((dd, ii) => {
        const delim = ii === 0 ? '' : ', ';
        tmp += `${delim}${dd}: "${args[dd].replace(/"/g, '')}"`;
    });
    tmp += '})';
    return tmp;
};
const templateEdge = (from, to) => {
    return `MATCH (from:GoTerm {id: '${from}'})
    MATCH (to:GoTerm {id: '${to}'})
    MERGE (from)-[rel:is_a]->(to)`;
};
const templateSymbol = (args) => {
    let tmp = 'CREATE (sy:Symbol {';
    Object.keys(args).forEach((dd, ii) => {
        const delim = ii === 0 ? '' : ', ';
        tmp += `${delim}${dd}: "${args[dd]}"`;
    });
    tmp += `})`;
    return tmp;
};
const templateEdgeGoa = (fromSymbol, toGoTerm, relName, args) => {
    const tmpArgs = Object.keys(args).reduce((p, c) => p += `${c}: "${args[c]}", `, "").slice(0, -2);
    return `MATCH (from:Symbol {name: '${fromSymbol}'})
    MATCH (to:GoTerm {id: '${toGoTerm}'})
    MERGE (from)-[rel:${relName} {${tmpArgs}}]->(to)`;
};
const readObo = (oboPath) => __awaiter(void 0, void 0, void 0, function* () {
    var e_1, _a;
    let delim = false;
    const vertexes = [];
    const edges = [];
    let result = {};
    try {
        for (var _b = __asyncValues(line$(oboPath)), _c; _c = yield _b.next(), !_c.done;) {
            const line = _c.value;
            if (line === '[Term]') {
                delim = true;
            }
            else if (line === '' && delim) {
                delim = false;
                vertexes.push(templateGTnode(result));
                if (result === null || result === void 0 ? void 0 : result.is_a) {
                    if (/^GO:[0-9]*/.test(result.is_a)) {
                        edges.push(templateEdge(result.id, result.is_a.match(/^GO:[0-9]*/)[0]));
                    }
                }
                result = {};
            }
            else if (delim)
                result[line.split(': ')[0]] = line.split(': ')[1].replace("\"", "");
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b);
        }
        finally { if (e_1) throw e_1.error; }
    }
    return { vertexes, edges };
});
const readGoa = (goaPath) => __awaiter(void 0, void 0, void 0, function* () {
    var e_2, _d;
    const header = [
        'database', 'ID', 'Symbol', 'Qualifier',
        'GO_Term', 'Evidence', 'Evidence_Code',
        'With', 'From', 'Name', 'Alternative_symbols',
        'Class', 'Taxon', 'Date', 'Origin'
    ];
    const vertexes = [];
    const edges = [];
    const allSymbols = {};
    try {
        for (var _e = __asyncValues(line$(goaPath)), _f; _f = yield _e.next(), !_f.done;) {
            const line = _f.value;
            if (/^[^!]/.test(line)) {
                const obj = line.split('\t').filter((e) => e).reduce((p, c, i) => (Object.assign(Object.assign({}, p), { [header[i]]: /*separator.test(c) ? c.split('|') :*/ c })), {});
                if (typeof allSymbols[obj.Symbol] === 'undefined') {
                    vertexes.push(templateSymbol({
                        name: obj.Symbol,
                        class: obj.Class,
                        fullName: obj.Name,
                        alternativeName: obj.Alternative_symbols,
                        taxon: obj.Taxon,
                        goaID: obj.ID,
                        goaDB: obj.Origin
                    }));
                    allSymbols[obj.Symbol] = '';
                }
                edges.push(templateEdgeGoa(obj.Symbol, obj.GO_Term, obj.Qualifier.replace("|", "_or_"), {
                    goaEvidence: obj.Evidence,
                    goaEvidenceCode: obj.Evidence_Code,
                    goaWith: obj.With,
                    goaFrom: obj.From,
                    goaDate: obj.Date
                }));
            }
        }
    }
    catch (e_2_1) { e_2 = { error: e_2_1 }; }
    finally {
        try {
            if (_f && !_f.done && (_d = _e.return)) yield _d.call(_e);
        }
        finally { if (e_2) throw e_2.error; }
    }
    return { vertexes, edges };
});
const runNeo = (session, sql) => {
    return new Promise((resolve, reject) => {
        try {
            session.run(sql).then((result) => resolve(result)).catch((err) => reject(err));
        }
        catch (error) {
            reject(error);
        }
    });
};
(() => __awaiter(void 0, void 0, void 0, function* () {
    const oboPath = '/home/thomas/NGS/ref/GO/go-basic.obo';
    const goaPath = '/home/thomas/NGS/ref/GO/goa_human.gaf';
    var driver = neo4j.driver('neo4j://localhost', neo4j.auth.basic('neo4j', '123456'));
    var session = driver.session();
    // OBO
    /*
    const rr = await readObo(oboPath)
    for (const v of rr.vertexes) {
        console.log('Inserting OBO vertexes...');
        await runNeo(session, v)
    }
    for (const e of rr.edges) {
        console.log('Inserting OBO edges...');
        await runNeo(session, e)
    }
    */
    // GOA
    const goaAll = yield readGoa(goaPath);
    console.log(goaAll.edges[0]);
    // for (const v of goaAll.vertexes) {
    //     console.log('Inserting GOA vertexes...');
    //     await runNeo(session, v)
    // }
    for (const e of goaAll.edges) {
        // console.log('Inserting GOA edges...');
        yield runNeo(session, e);
    }
    yield driver.close();
}))();
