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';

Meteor.methods({
    'sqlite2mongo' (sqliteAddress) {
        this.unblock();
        check(sqliteAddress, String);

        if (this.userId) {
            TransliterationDb.remove({});
            let dbFullAddress = Meteor.rootPath + "/" + sqliteAddress;
            const promise = select(dbFullAddress, "transliteration_1")
                .then((documentArray) => {

                    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, rresult) {
                                // do something with result
                            });
                            bulkOp = TransliterationDb.rawCollection().initializeUnorderedBulkOp();
                        }
                    }
                    // Clean up queues
                    if (counter % 1000 != 0) {
                        bulkOp.execute(function(e, result) {
                            // do something with result
                        });
                    }
                    return true;
                }).catch((e) => {
                    throw new Meteor.Error('500', e);
                });
            return promise.await();

        }
    }
});


function select(database, table) {
    return new Promise((resolve, reject) => {
        const db = new sqlite3.Database(database);
        const queries = [];

        db.each(`SELECT * FROM ${table}`, (err, row) => {
            if (err) {
                reject(err); // optional: you might choose to swallow errors.
            } else {
                queries.push(row); // accumulate the data
            }
        }, (err, n) => {
            if (err) {
                reject(err); // optional: again, you might choose to swallow this error.
            } else {
                resolve(queries); // resolve the promise
            }
        });
    });
}