import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { Mongo } from 'meteor/mongo';
const sqlite3 = require('sqlite3').verbose();
import TransliterationDb from '../collections/transliterationdb.js';

import { Logger } from 'meteor/ostrio:logger';
import { LoggerFile } from 'meteor/ostrio:loggerfile';

var log = new Logger();
(new LoggerFile(log)).enable();

Meteor.methods({
    'sqlite2mongo' (sqliteAddress) {
        this.unblock();
        Meteor.settings.enableDebug ? log.debug(`sqlite2mongo() => start sqlite2mongo `, sqliteAddress) : '';
        check(sqliteAddress, String);

        if (this.userId) {
            Meteor.settings.enableDebug ? log.debug(`sqlite2mongo() => start remove uploaded databases`, sqliteAddress, Meteor.user().username) : '';

            TransliterationDb.remove({});
            Meteor.settings.enableDebug ? log.debug(`sqlite2mongo() => uploaded databases have been removed`, sqliteAddress, Meteor.user().username) : '';

            let dbFullAddress = Meteor.rootPath + "/" + sqliteAddress;
            Meteor.settings.enableDebug ? log.debug(`sqlite2mongo() => database upload root is ${dbFullAddress}`, {}, Meteor.user().username) : '';

            const promise = select(dbFullAddress, "transliteration_1")
                .then((documentArray) => {
                    Meteor.settings.enableDebug ? log.debug(`sqlite2mongo() => start inserting fetched documents into mongodb`, documentArray.length, Meteor.user().username) : '';
                    let bulkOp = TransliterationDb.rawCollection().initializeUnorderedBulkOp(),
                        counter = 0;

                    for (let data of documentArray) {

                        bulkOp.insert(data);

                        counter++;
                        // Send to server in batch of 1000 insert operations
                        if (counter % 1000 == 0) {
                            // Execute per 1000 operations and re-initialize every 1000 update statements
                            bulkOp.execute(function(e, result) {
                                // Meteor.settings.enableDebug ? log.debug(`sqlite2mongo() => ${counter} records have been inserted into mongodb`, counter, Meteor.user().username) : '';
                            });
                            bulkOp = TransliterationDb.rawCollection().initializeUnorderedBulkOp();
                        }
                    }
                    // Clean up queues
                    if (counter % 1000 != 0) {
                        bulkOp.execute(function(e, result) {
                            // Meteor.settings.enableDebug ? log.debug(`sqlite2mongo() => ${counter} records have been inserted into mongodb`, counter, Meteor.user().username) : '';
                        });
                    }
                    Meteor.settings.enableDebug ? log.debug(`sqlite2mongo() => insertion into mongodb have done`, counter, Meteor.user().username) : '';
                    return true;
                }).catch((e) => {
                    log.error(`sqlite2mongo() => error in fetching records from sqlite db`, e, Meteor.user().username);
                    throw new Meteor.Error('500', e);
                });
            return promise.await();

        }
    }
});


function select(database, table) {
    // Meteor.settings.enableDebug ? log.debug(`sqlite2mongo() => start select db records`, { database, table }, Meteor.user().username) : '';
    return new Promise((resolve, reject) => {
        // Meteor.settings.enableDebug ? log.debug(`sqlite2mongo() => connect to uploaded db`, { database, table }, Meteor.user().username) : '';
        const db = new sqlite3.Database(database);
        const queries = [];
        // Meteor.settings.enableDebug ? log.debug(`sqlite2mongo() => start query db records`, { database, table }, Meteor.user().username) : '';
        db.each(`SELECT * FROM ${table}`, (err, row) => {
            if (err) {
                // log.error(`sqlite2mongo() => 1.error in fetching records from sqlite db`, err, Meteor.user().username);
                reject(err);
            } else {
                queries.push(row);
            }
        }, (err, n) => {
            if (err) {
                // log.error(`sqlite2mongo() => 2.error in fetching records from sqlite db`, err, Meteor.user().username);
                reject(err);
            } else {
                // Meteor.settings.enableDebug ? log.debug(`sqlite2mongo() => fetching from db have been done`, queries, Meteor.user().username) : '';
                resolve(queries);
            }
        });
    });
}


Meteor.settings.enableDebug ? log.debug(`endof translitdb`) : '';