<commit_before>// {{{ SETUP
var http = require('http');
var fs = require('fs');
var mysql = require('mysql');
_ = require('underscore');
d3 = require("d3");
require("../binnedData.js");
require("./database.js");
//require("./couchAccess.js");

var cradle = require('cradle')
var db = new(cradle.Connection)().database('bridge_test');

function saveToCouch(id, data) {
    console.log("saveToCouch");
    db.save(id, {
        data: data
    }, function (err, res) {
        if (err) {
            //Handle error
            console.log("saving ERROR");
        } else {
            // Handle success
            console.log("saving success");
        }
    });
}

red = '\033[31m';
yellow = '\033[33m';
magenta = '\033[35m';
blue = '\033[36m';
reset = '\033[0m';

function dt (num) {
    var newdate = new Date();
    newdate.setTime(num);
    return newdate;
}

var MAX_NUMBER_OF_BIN_LEVELS = 46; // keep sync'd with ../binnedChart.js and scraper.js
var WHICH_GIRDER = "ESGgirder18";
// SETUP }}}

// {{{ GLOBAL VARIABLES
var binData = binnedData();
// GLOBAL VARIABLES}}}

// {{{ COMMAND LINE INPUT
if (process.argv[9] === undefined) {
    console.log("USAGE:");
    console.log("  start_year(YYYY) start_month(0-11) start_day(1-31) start_hour(0-23)");
    console.log("  end_year(YYYY) end_month(0-11) end_day(1-31) end_hour(0-23)");
    return
}

var start_year  = process.argv[2];
var start_month = process.argv[3];
var start_day   = process.argv[4];
var start_hour  = process.argv[5];

var end_year  = process.argv[6];
var end_month = process.argv[7];
var end_day   = process.argv[8];
var end_hour  = process.argv[9];
// COMMAND LINE INPUT }}}

// {{{ WHERE TO WALK
var lowestLevelToKeep = 6;

var rangeToWalk = [(new Date(start_year, start_month, start_day, start_hour)).getTime(),
    (new Date(end_year, end_month, end_day, end_hour)).getTime()];

if (rangeToWalk[0] >= rangeToWalk[1]) {
    console.log("we already have that time span");
    return;
}

var stepSize = 60000; // 10000 is 2400 samples each time
// 60000 is 1 minute each time
// 100000 is 1:40 each time
// 600000 is ten minutes each time (works best for binning 1.0)

// WHERE TO WALK }}}

function async(arg, callback) {
  console.log('do something with \''+arg+'\', return 0.1 sec later');
  setTimeout(function() { callback(arg); }, 100);
}

//sendQuery("asdfasdfasdfasdf", function () {
//    console.log("working?");
//});

function sendQuery(query, callback) {
    sendDatabaseQuery(query, function (queryResult) {
        // Bin the new data
        console.log("- data received. binning data...");
        if(queryResult == null) {
            callback();
            return;
        }
        try {
            binData.addRawData(queryResult);

            // Delete the bottom few levels
            binData.removeAllLevelsBelow(lowestLevelToKeep);
        } catch (e) {
            console.log(magenta+"=*= ERROR =*="+reset, e.message);
            throw e;
        }
        console.log("...done binning");
        callback();
    });
}

var results = [];
function series(item) {
    if(item) {
        var query = makeQuery(item, item+stepSize);
        results.push(results);
        sendQuery( query, function() {
            // TODO: get results from mysql and add them to binData.
            console.log("working??");
            return series(walk_steps.shift());
        });
    } else {
        return final();
    }
}

var walk_steps = [];
for(var i = rangeToWalk[0]; i < rangeToWalk[1]; i = i + stepSize) {
    walk_steps.push(i);
}

// Run the series
series(walk_steps.shift());

// Final task (same in all the examples)
function final() {
    // TODO: save it out to couchdb
    saveIt();
    console.log('Done');
    //process.exit(0);
}

return;

// TODO: walk through each section of the database
for (var i = rangeToWalk[0]; i < rangeToWalk[1]; i = i + stepSize) {
    var reset_it = false;

    var query = makeQuery(i, i+stepSize);

    console.log("WAIT_TOO");

    sendDatabaseQuery(query, function (queryResult, res) {
        // Bin the new data
        console.log("- data received. binning data...");
        try {
            binData.addRawData(queryResult);

            // Delete the bottom few levels
            binData.removeAllLevelsBelow(lowestLevelToKeep);
        } catch (e) {
            console.log(magenta+"=*= ERROR =*="+reset, e.message);
            throw e;
        }
        console.log("...done binning");
    }, reset_it);
}

function createIDString(girder, key, level, ms_start) {
    // returns the ID which the couchdb database will use.
    return "" + girder + "-" + key + "-" + level + "-" + ms_start;
}

function saveIt() {
    console.log("trying to save now");

    var something = false;

    for (var ke in binData.getKeys()) { // for each key
        var k = binData.getKeys()[ke];

        for (var l = lowestLevelToKeep; l < MAX_NUMBER_OF_BIN_LEVELS; l++) { // for each level
            if (!binData.bd()[k]) {
                console.log('continue:', k);
                continue;
            }

            for (var c in binData.bd()[k].levels[l]) { // for each bin container
                something = true;
                var id = createIDString(WHICH_GIRDER, k, l, c);
                var dat = binData.bd()[k].levels[l][c];
                console.log("saving:", id, "to couchDB");
                saveToCouch(id, dat);
                //var currentBinContainer = binData.bd()[key].levels[level][ms_start]
            }
        }
    }

    if (!something) {
        console.log("stop waiting. nothing to save");
    }
}

function saveItOld (st, en) {
    // Save binData to a file
    var x = binData.toString();

    var saveName = "/Users/woelk/scraped_2.1_6/scraped_piece_"+lowestLevelToKeep
    +"_"+st[0]+"-"+st[1]+"-"+st[2]+"-"+st[3]
    +"_"+en[0]+"-"+en[1]+"-"+en[2]+"-"+en[3]

    fs.writeFile(saveName, x, function(err) {
        if(err) {
            console.log(err);
        } else {
            console.log("The file was saved to"+saveName);
        }
    });
}

/* vim: set foldmethod=marker: */
<commit_msg>little refactoring<commit_after>// {{{ SETUP
var http = require('http');
var fs = require('fs');
var mysql = require('mysql');
_ = require('underscore');
d3 = require("d3");
require("../binnedData.js");
require("./database.js");
//require("./couchAccess.js");

var cradle = require('cradle')
var db = new(cradle.Connection)().database('bridge_test');

function saveToCouch(id, data) {
    console.log("saveToCouch");
    db.save(id, {
        data: data
    }, function (err, res) {
        if (err) {
            //Handle error
            console.log("saving ERROR");
        } else {
            // Handle success
            console.log("saving success");
        }
    });
}

red = '\033[31m';
yellow = '\033[33m';
magenta = '\033[35m';
blue = '\033[36m';
reset = '\033[0m';

function dt (num) {
    var newdate = new Date();
    newdate.setTime(num);
    return newdate;
}

var MAX_NUMBER_OF_BIN_LEVELS = 46; // keep sync'd with ../binnedChart.js and scraper.js
var WHICH_GIRDER = "ESGgirder18";
// SETUP }}}

// {{{ GLOBAL VARIABLES
var binData = binnedData();
// GLOBAL VARIABLES}}}

// {{{ COMMAND LINE INPUT
if (process.argv[9] === undefined) {
    console.log("USAGE:");
    console.log("  start_year(YYYY) start_month(0-11) start_day(1-31) start_hour(0-23)");
    console.log("  end_year(YYYY) end_month(0-11) end_day(1-31) end_hour(0-23)");
    return
}

var start_year  = process.argv[2];
var start_month = process.argv[3];
var start_day   = process.argv[4];
var start_hour  = process.argv[5];

var end_year  = process.argv[6];
var end_month = process.argv[7];
var end_day   = process.argv[8];
var end_hour  = process.argv[9];
// COMMAND LINE INPUT }}}

// {{{ WHERE TO WALK
var lowestLevelToKeep = 6;

var rangeToWalk = [(new Date(start_year, start_month, start_day, start_hour)).getTime(),
    (new Date(end_year, end_month, end_day, end_hour)).getTime()];

if (rangeToWalk[0] >= rangeToWalk[1]) {
    console.log("we already have that time span");
    return;
}

var stepSize = 60000; // 10000 is 2400 samples each time
                      // 60000 is 1 minute each time
                      // 100000 is 1:40 each time
                      // 600000 is ten minutes each time (works best for binning 1.0)

// WHERE TO WALK }}}

function async_function_example(arg, callback) {
  console.log('do something with \''+arg+'\', return 0.1 sec later');
  setTimeout(function() { callback(arg); }, 100);
}

//Heavy inspiration from: http://book.mixu.net/ch7.html
function sendQuerySync(item, callback) {
    var query = makeQuery(item, item+stepSize);

    sendDatabaseQuery(query, function (queryResult) {
        // Bin the new data
        console.log("- data received. binning data...");
        if(queryResult == null) {
            callback();
            return;
        }
        try {
            binData.addRawData(queryResult);

            // Delete the bottom few levels
            binData.removeAllLevelsBelow(lowestLevelToKeep);
        } catch (e) {
            console.log(magenta+"=*= ERROR =*="+reset, e.message);
            throw e;
        }
        console.log("...done binning");
        callback();
    });
}

function series(item, func) {
    if(item) {
        func(item, function() {
            return series(walk_steps.shift(), func);
        });
    } else {
        return saveIt(final);
    }
}

var walk_steps = [];
for(var i = rangeToWalk[0]; i < rangeToWalk[1]; i = i + stepSize) {
    walk_steps.push(i);
}

// Run the series
series(walk_steps.shift(), sendQuerySync);

// Final task (same in all the examples)
function final() {
    // TODO: save it out to couchdb
    console.log('Done');
    //process.exit(0);
}

return;

// TODO: walk through each section of the database
for (var i = rangeToWalk[0]; i < rangeToWalk[1]; i = i + stepSize) {
    var reset_it = false;

    var query = makeQuery(i, i+stepSize);

    console.log("WAIT_TOO");

    sendDatabaseQuery(query, function (queryResult, res) {
        // Bin the new data
        console.log("- data received. binning data...");
        try {
            binData.addRawData(queryResult);

            // Delete the bottom few levels
            binData.removeAllLevelsBelow(lowestLevelToKeep);
        } catch (e) {
            console.log(magenta+"=*= ERROR =*="+reset, e.message);
            throw e;
        }
        console.log("...done binning");
    }, reset_it);
}

function createIDString(girder, key, level, ms_start) {
    // returns the ID which the couchdb database will use.
    return "" + girder + "-" + key + "-" + level + "-" + ms_start;
}

function makeListForCouch(item) {
    // TODO: store a global list, adding things that couch should send
    // TODO: then synchronously send them out using magic
}

function saveIt(callback) {
    console.log("trying to save now");

    var something = false;

    for (var ke in binData.getKeys()) { // for each key
        var k = binData.getKeys()[ke];

        for (var l = lowestLevelToKeep; l < MAX_NUMBER_OF_BIN_LEVELS; l++) { // for each level
            if (!binData.bd()[k]) {
                console.log('continue:', k);
                continue;
            }

            for (var c in binData.bd()[k].levels[l]) { // for each bin container
                something = true;
                var id = createIDString(WHICH_GIRDER, k, l, c);
                var dat = binData.bd()[k].levels[l][c];
                console.log("saving:", id, "to couchDB");
                saveToCouch(id, dat);
                //var currentBinContainer = binData.bd()[key].levels[level][ms_start]
            }
        }
    }

    if (!something) {
        console.log("there was nothing to save");
    }
}

function saveItOld (st, en) {
    // Save binData to a file
    var x = binData.toString();

    var saveName = "/Users/woelk/scraped_2.1_6/scraped_piece_"+lowestLevelToKeep
    +"_"+st[0]+"-"+st[1]+"-"+st[2]+"-"+st[3]
    +"_"+en[0]+"-"+en[1]+"-"+en[2]+"-"+en[3]

    fs.writeFile(saveName, x, function(err) {
        if(err) {
            console.log(err);
        } else {
            console.log("The file was saved to"+saveName);
        }
    });
}

/* vim: set foldmethod=marker: */
<|endoftext|>


<commit_before>'use strict'
/**
 * Created by acastillo on 7/1/16.
 */
define(['src/util/api', 'src/util/ui', 'OCLE', 'ExpandableMolecule','elnPlugin', 'Roc'], function (API, UI, OCLE, ExpandableMolecule, elnPlugin, Roc) {

    function actionHandler(action, options){
        var opt = Object.assign({},{roc:API.cache('roc'),couchDB:API.cache('couchDB')},options)
        var roc = opt.roc;
        var couchDB = options.couchDB;
        if(!couchDB){
            console.log("You need a couchDB target for this. Please define a couchUrl optional variable specifiying: database, kind and user before to try this");
            return;
        }
        var uuid = couchDB.uuid;

        if (!roc && uuid) {
            var couchUrl = couchDB.couchUrl;
            var database = couchDB.database;
            roc = new Roc({
                url: couchUrl,
                database: database,
                processor: elnPlugin,
                kind: couchDB.kind
            });

            roc.document(uuid, {
                varName: 'sample'
            }).then(function (sample) {
                var sampleVar = API.getVar('sample');

                API.createData('annot1d', null);
                API.createData('annot2d', null);
                API.setVariable('sampleCode', sampleVar, ['$id', 0]);
                API.setVariable('creationDate', sampleVar, ['$creationDate']);
                API.setVariable('modificationDate', sampleVar, ['$modificationDate']);
                API.setVariable('content', sampleVar, ['$content']);
                API.setVariable('molfile', sampleVar, ['$content', 'general', 'molfile']);
                API.setVariable('mf', sampleVar, ['$content', 'general', 'mf']);
                API.setVariable('mw', sampleVar, ['$content', 'general', 'mw']);
                API.setVariable('description', sampleVar, ['$content', 'general', 'description']);
                API.setVariable('iupac', sampleVar, ['$content', 'general', 'iupac']);
                API.setVariable('bp', sampleVar, ['$content', 'physical', 'bp']);
                API.setVariable('nd', sampleVar, ['$content', 'physical', 'nd']);
                API.setVariable('mp', sampleVar, ['$content', 'physical', 'mp']);
                API.setVariable('density', sampleVar, ['$content', 'physical', 'density']);
                API.setVariable('nmr', sampleVar, ['$content', 'spectra', 'nmr']);
                API.setVariable('ir', sampleVar, ['$content', 'spectra', 'ir']);
                API.setVariable('mass', sampleVar, ['$content', 'spectra', 'mass']);
                updateAttachments(sample);

                var expandableMolecule = new ExpandableMolecule(sample);
                API.cache('expandableMolecule', expandableMolecule);
                if(typeof IframeBridge !='undefined'){
                    sample.onChange(function (event) {
                        IframeBridge.postMessage('tab.status', {
                            saved: false
                        });
                    });
                }

            });

            API.cache('roc', roc);

            if (!roc) return;

            var sample = API.getData('sample');

            if (action) {
                switch (action.name) {
                    case 'refresh':
                        roc.get(uuid);
                        break;
                    case 'save':
                        roc.update(sample).then(function () {
                            sample.onChange(function (event) {
                                IframeBridge.postMessage('tab.status', {
                                    saved: true
                                });
                            });
                        });
                        break;
                    default:
                        break
                }
            }
        }

        function updateAttachments(entry) {
            return roc.getAttachmentList(couchDB.uuid).then(function (list) {
                API.createData('sampleAttachments', list);
            })
        }
    }

    return actionHandler;
});
<commit_msg>opt by options<commit_after>'use strict'
/**
 * Created by acastillo on 7/1/16.
 */
define(['src/util/api', 'src/util/ui', 'OCLE', 'ExpandableMolecule','elnPlugin', 'Roc'], function (API, UI, OCLE, ExpandableMolecule, elnPlugin, Roc) {

    function actionHandler(action, options){
        var opt = Object.assign({},{roc:API.cache('roc'),couchDB:API.cache('couchDB')},options)
        var roc = opt.roc;
        var couchDB = opt.couchDB;
        if(!couchDB){
            console.log("You need a couchDB target for this. Please define a couchUrl optional variable specifiying: database, kind and user before to try this");
            return;
        }
        var uuid = couchDB.uuid;

        if (!roc && uuid) {
            var couchUrl = couchDB.couchUrl;
            var database = couchDB.database;
            roc = new Roc({
                url: couchUrl,
                database: database,
                processor: elnPlugin,
                kind: couchDB.kind
            });

            roc.document(uuid, {
                varName: 'sample'
            }).then(function (sample) {
                var sampleVar = API.getVar('sample');

                API.createData('annot1d', null);
                API.createData('annot2d', null);
                API.setVariable('sampleCode', sampleVar, ['$id', 0]);
                API.setVariable('creationDate', sampleVar, ['$creationDate']);
                API.setVariable('modificationDate', sampleVar, ['$modificationDate']);
                API.setVariable('content', sampleVar, ['$content']);
                API.setVariable('molfile', sampleVar, ['$content', 'general', 'molfile']);
                API.setVariable('mf', sampleVar, ['$content', 'general', 'mf']);
                API.setVariable('mw', sampleVar, ['$content', 'general', 'mw']);
                API.setVariable('description', sampleVar, ['$content', 'general', 'description']);
                API.setVariable('iupac', sampleVar, ['$content', 'general', 'iupac']);
                API.setVariable('bp', sampleVar, ['$content', 'physical', 'bp']);
                API.setVariable('nd', sampleVar, ['$content', 'physical', 'nd']);
                API.setVariable('mp', sampleVar, ['$content', 'physical', 'mp']);
                API.setVariable('density', sampleVar, ['$content', 'physical', 'density']);
                API.setVariable('nmr', sampleVar, ['$content', 'spectra', 'nmr']);
                API.setVariable('ir', sampleVar, ['$content', 'spectra', 'ir']);
                API.setVariable('mass', sampleVar, ['$content', 'spectra', 'mass']);
                updateAttachments(sample);

                var expandableMolecule = new ExpandableMolecule(sample);
                API.cache('expandableMolecule', expandableMolecule);
                if(typeof IframeBridge !='undefined'){
                    sample.onChange(function (event) {
                        IframeBridge.postMessage('tab.status', {
                            saved: false
                        });
                    });
                }

            });

            API.cache('roc', roc);

            if (!roc) return;

            var sample = API.getData('sample');

            if (action) {
                switch (action.name) {
                    case 'refresh':
                        roc.get(uuid);
                        break;
                    case 'save':
                        roc.update(sample).then(function () {
                            sample.onChange(function (event) {
                                IframeBridge.postMessage('tab.status', {
                                    saved: true
                                });
                            });
                        });
                        break;
                    default:
                        break
                }
            }
        }

        function updateAttachments(entry) {
            return roc.getAttachmentList(couchDB.uuid).then(function (list) {
                API.createData('sampleAttachments', list);
            })
        }
    }

    return actionHandler;
});
<|endoftext|>


<commit_before>window.addEventListener('devicelight', (...args) => this.ambientlightListener(...args))
<commit_msg>include DecibelMeter Library<commit_after>var DecibelMeter = ( function ( window, navigator, document, undefined ) {

	// user media

	if (!navigator.getUserMedia)
		navigator.getUserMedia = navigator.webkitGetUserMedia
								|| navigator.mozGetUserMedia
								|| navigator.msGetUserMedia;

	if (!navigator.getUserMedia) {
		throw new Error('DecibelMeter: getUserMedia not supported');
		return undefined;
	}

	// audio context

	window.AudioContext = window.AudioContext || window.webkitAudioContext;

	if (!window.AudioContext) {
		throw new Error('DecibelMeter: AudioContext not supported');
		return undefined;
	}

	// audio sources

	if (!navigator.mediaDevices) {
		throw new Error('DecibelMeter: mediaDevices not supported');
		return undefined;
	}

	if (!navigator.mediaDevices.enumerateDevices) {
		throw new Error('DecibelMeter: mediaDevices.enumerateDevices() not supported');
		return undefined;
	}

	var sources = [],
		sourcesIndex = {},
		sourcesReady = false;

	navigator.mediaDevices.enumerateDevices()
	.then(function(devices) {

	  devices.forEach( function (source) {
		  if (source.kind === 'audioinput') {
			  sources.push(source);
			  sourcesIndex[source.deviceId] = source;
		  }
	  });

	  sourcesReady = true;

	  // let meters know that audio sources are ready now

	  meters.forEach(function (meter) {
		  dispatch(meter, 'ready', [meter, sources]);
	  });
	})
	.catch(function(err) {
	  console.log(err.name + ": " + err.message);
	});

	// util

	function connectTo(source, meter, callback) {

		var oldSource = meter.source,
			changing = oldSource !== null,
			constraints = { audio: { optional: [{sourceId: source.id}] } };

		meter.source = source;

		function success(stream) {
			var connection = {};

			connection.stream = stream;
			connection.context = new AudioContext();
			connection.source = connection.context.createMediaStreamSource(stream);
			connection.analyser = connection.context.createAnalyser();
			connection.analyser.smoothingTimeConstant = .5;
			connection.analyser.frequencyBinCount = 16;
			connection.lastSample = new Uint8Array(1);

			meter.connection = connection;
			meter.connected = true;

			if (callback)
				callback.call(meter, meter, source);

			if (changing && meter.handle.sourceChange)
				dispatch(meter, 'source-change', [source, oldSource, meter]);

			if (meter.handle.connect)
				dispatch(meter, 'connect', [meter, source]);
		}

		function error() {
			alert('Error connecting to source');
		}

		navigator.getUserMedia(constraints, success, error);
	}

	function dispatch(meter, eventName, params) {
		var h = meter.handle[eventName],
			n = h.length;

		if (n === 0) return;

		var i = 0;

		for (; i < n; i++)
			if (true === h[i].apply(meter, params))
				break;
	}

	// class

	function DecibelMeter(id, opts) {
		this.id = id;
		this.opts = opts;
		this.source = null;
		this.listening = false;
		this.connection = null;
		this.connected = false;
		this.handle = {
			ready:              opts.ready ? [opts.ready] : [],
			sample:             opts.sample ? [opts.sample] : [],
			connect:            opts.connect ? [opts.connect] : [],
			disconnect:         opts.disconnect ? [opts.disconnect] : [],
			"source-change":    opts.sourceChange ? [opts.sourceChange] : [],
			listen:             opts.listen ? [opts.listen] : [],
			"stop-listening":   opts.stopListeing ? [opts.stopListening] : []
		};

		this.startLoop();
	}

	DecibelMeter.prototype.getSources = function () {
		return sources;
	};

	DecibelMeter.prototype.connect = function (source, callback) {

		if (!sourcesReady)
			throw new Error('DecibelMeter: Audio sources not ready');

		if (!source)
			throw new Error('DecibelMeter: No audio source specified');

		if (typeof source === 'string' || typeof source === 'number') {

			source = sourcesIndex[source];

			if (!source)
				throw new Error('DecibelMeter: Attempted to select invalid audio source');
		}

		if (this.source === source) return; // already connected to this source

		connectTo(source, this, callback);
		return this;
	};

	DecibelMeter.prototype.disconnect = function () {
		if (this.connection === null) return this;

		this.stopListening();
		this.connection.stream.stop();
		this.connection.stream = null;
		this.connection = null;
		this.source = null;
		this.connected = false;

		dispatch(this, 'disconnect', [this]);

		return this;
	};

	DecibelMeter.prototype.listen = function () {
		if (this.listening) return;

		if (this.source === null)
			throw new Error('DecibelMeter: No source selected');

		if (this.connection === null)
			throw new Error('DecibelMeter: Not connected to source');

		this.connection.source.connect(this.connection.analyser);
		this.listening = true;

		dispatch(this, 'listen', [this]);
	};

	DecibelMeter.prototype.stopListening = function () {
		if (!this.listening) return;

		if (this.source === null)
			throw new Error('DecibelMeter: No source selected');

		if (this.connection === null)
			throw new Error('DecibelMeter: Not connected to source');

		this.connection.source.disconnect(this.connection.analyser);
		this.listening = false;

		dispatch(this, 'stop-listening', [this]);
	};

	DecibelMeter.prototype.startLoop = function () {

		var meter = this;

		function update() {

			if (meter.listening && meter.handle.sample) {

				meter.connection.analyser.getByteFrequencyData(meter.connection.lastSample);

				var value = meter.connection.lastSample[0],
					percent = value / 255,
					dB = meter.connection.analyser.minDecibels + ((meter.connection.analyser.maxDecibels - meter.connection.analyser.minDecibels) * percent);

				dispatch(meter, 'sample', [dB, percent, value]);
			}

			requestAnimationFrame(update);
		}

		update();
	};

	DecibelMeter.prototype.on = function (eventName, handler) {
		if (this.handle[eventName] === undefined) return this;
		this.handle[eventName].push(handler);
		return this;
	};

	// api

	var meters = [],
		metersIndex = {};

	return {
		create: function (id, opts) {
			id = id || ['db', new Date().getTime(), Math.random()].join('-');
			var meter = new DecibelMeter(id, opts || {});
			metersIndex[id] = meter;
			meters.push(meter);
			return meter;
		},

		getMeterById: function (id) {
			return metersIndex[id] || null;
		},

		getMeters: function () {
			return meters;
		}
	};

})( window, navigator, document );

window.addEventListener('devicelight', (...args) => this.ambientlightListener(...args))
<|endoftext|>


<commit_before>$.extend(doaj, {
    af: {
        active: false,

        newApplicationForm: (params) => {
            return edges.instantiate(doaj.af.ApplicationForm, params);
        },
        ApplicationForm: function(params) {
            this.currentTab = params.hasOwnProperty("currentTab") ? params.currentTab : 0;
            this.previousTab = params.hasOwnProperty("previousTab") ? params.previousTab : 0;

            this.form = $(".application_form");
            this.context = this.form.attr("context");
            this.tabs = $(".tab");
            this.sections = $(".form-section");

            this.tabValidationState = [];

            this.jq = (selector) => {
                return $(selector, this.form);
            };

            this.init = () => {
                this.jq("input, select").each((idx, inp) => {
                    let name = $(inp).attr("name");
                    // console.log(name);
                    if (name) {
                        name = name.split("-");
                        $(inp).attr("data-parsley-errors-container", "#" + name[0] + "_checkbox-errors");
                    }
                });

                let reviewedSelector = this.jq("#reviewed");
                edges.on(reviewedSelector, "click", this, "manage_review_checkboxes");
                // $("#reviewed").on("click", doaj.af.manage_review_checkboxes);

                for (let i = 0; i < this.tabs.length; i++) {
                    this.tabValidationState.push({"state" : "unvalidated"});
                }

                this.prepareSections();
                // this.usePaginationMenu();

                // Display the current tab
                if (this.context === "admin") {
                    // this.setup_maned();
                }
                // $(".application_form").parsley().validate();
                //this.currentTab = -1;
                //for (let i = 0; i < this.tabs.length; i++) {
                //    this.next();
                    // showTab(i);
                //}
                // this.currentTab = 0;
                this.showTab(this.currentTab);

                let nextSelector = this.jq("#nextBtn");
                let prevSelector = this.jq("#prevBtn");
                let submitSelector = this.jq("#submitBtn");
                let draftSelector = this.jq("#saveDraft");

                edges.on(nextSelector, "click", this, "next");
                edges.on(prevSelector, "click", this, "prev");
                edges.on(submitSelector, "click", this, "submitapplication");
                edges.on(draftSelector, "click", this, "savedraft");
            };

            this.showTab = (n) => {
                // This function will display the specified tab of the form ...
                //hide all other tabs
                // if (n < this.sections.length-1){
                //     let hiddenField = this.jq("#validated-" + n);
                //     if (hiddenField.val() === "") {
                //         hiddenField.val("False");
                //     }
                // }

                this.tabs.each((idx, tab) => {
                    $(tab).hide();
                });

                let submitButton = this.jq("#submitBtn");
                let draftButton = this.jq("#draftBtn");
                $(this.tabs[n]).show();
                this.jq("#cannot_save_draft").hide();
                submitButton.hide();
                draftButton.show();
                // ... and fix the Previous/Next buttons:
                if (n === 0) {
                    this.jq("#prevBtn").hide();
                } else {
                    this.jq("#prevBtn").show();
                }

                if (n === (this.tabs.length - 1)) {
                    //show submit button only if all tabs are validated
                    this.jq("#nextBtn").hide();
                    submitButton.hide();
                    draftButton.show();
                    let validated = this.form_validated();
                    if (!validated) {
                        this.jq("#cannot-submit-invalid-fields").show();
                    } else {
                        this.jq("#cannot-submit-invalid-fields").hide();
                        submitButton.show();
                    }

                } else {
                    let nextBtn = this.jq("#nextBtn");
                    nextBtn.show();
                    nextBtn.html("Next");
                    submitButton.hide();
                    draftButton.show();
                }
                this.currentTab = n;
                this.previousTab = n-1;
                // ... and run a function that displays the correct step indicator:
                if(n === this.tabs.length - 1) {
                    // this.jq("#validated-" + n).val("True");
                    this.prepareReview()
                }
                if (this.context === "admin") {
                    // this.modify_view();
                }
                else if (this.context === "public") {
                    this.updateStepIndicator();
                    // this.fixStepIndicator(n)
                }
                window.scrollTo(0,0);
            };

            this.prepareReview = () => {
                let review_values = $("td[id$='__review_value']");
                review_values.each((idx, question) => {
                    let id = $(question).attr('id');
                    // TODO: think about how to generalise this.  If we add more fields like this or
                    // change the apc_charges bit then it will need updating
                    if (id === "apc_charges__review_value") {
                        let currency = $("select[id$='apc_currency']");
                        let max = $("input[id$='apc_max']");
                        let result = "";
                        let isValid = true;
                        for (let i = 0; i < currency.length; i++){
                            let curr = $(currency[i]).find('option:selected').text();
                            let m = $(max[i]).val();
                            if (m !== "" || curr !== "") {
                                result += (m === "" ? "" : m) + " " + (curr === "" ? "" : curr) + " " + "
";
                            }
                        }
                        if ($(max[0]).parsley().validationResult !== true || ($(currency[0]).parsley().validationResult !== true)) {
                            isValid = false;
                        }
                        if (result === "" && isValid){
                            $(question).parent().hide();
                        }
                        else {
                            $(question).parent().show();
                            $(question).html(result);
                        }
                    }
                    else {
                        let name = id.substring(0, id.indexOf("__review_value"));
                        let input = $("input[name^='" + name + "']");
                        if (input.length === 0) {  //it's not input but select
                            input = $("[name^='" + name + "']");
                            let result = "";
                            input.each((idx, inp) => {
                                let val = $(inp).find('option:selected').text();
                                if (val !== "") {
                                    result += val + "
";
                                }

                            });
                            $(question).html(result);
                        } else {
                            if (id === "keywords__review_value") {
                                let result = "";
                                let this_input = $('#keywords');
                                let keywords = this_input.val().split(",");
                                if (keywords.length !== 1) {
                                    $(keywords).each((idx, kw) => {
                                        result += kw + "
";
                                    });
                                }
                                else {
                                    result = keywords[0];
                                }
                                $(question).html(result);

                            } else {
                                if ($(input).attr("data-parsley-required-if") !== undefined) {
                                    if (input.val() === "" && $(input).parsley().validationResult === true){
                                        $(question).parent().hide();
                                        return;
                                    }
                                    else {
                                        $(question).parent().show();
                                    }
                                }
                                let type = input.attr("type");
                                if (type === "text" || type === "number") {
                                    $(question).html(input.val())
                                } else if (type === "url") {
                                    $(question).html('' + input.val() + '')
                                } else if (type === "radio") {
                                    if (input.is(":checked")) {
                                        let text = $('label[for=' + $(input.filter(':checked')).attr('id') + ']').text();
                                        $(question).html(text);
                                    }
                                } else if (type === "checkbox") {
                                    let result = '';
                                    input.each((idx, i) => {
                                        if ($(i).is(":checked")) {
                                            let text = $('label[for=' + $(i).attr('id') + ']').text();
                                            result += text + "
";
                                        }
                                    });
                                    $(question).html(result)
                                }
                            }
                        }
                    }

                })
            };

            this.form_validated = () => {
                let result = true;
                let inputs = this.jq("[name^='validated']");
                $(inputs).each((idx, input) => {
                    if (idx === inputs.length-1) {
                        return result;
                    }
                    if ($(input).val() !== "True") {
                        result = false;
                        return;
                    }
                });
                return result;
            };

            this.next = () => {
                this.navigate(this.currentTab + 1);
            };

            this.prev = () => {
                this.navigate(this.currentTab - 1, true);
            };

            this.submitaplication = () => {
                let parsleyForm = this.form.parsley();
                this.form.submit();
            };

            this.savedraft = () => {
                this.form.attr('novalidate', 'novalidate');
                var draftEl = $("input[name=draft]");
                if (draftEl.length === 0) {
                    let input = $("<input>")
                       .attr("type", "hidden")
                       .attr("name", "draft").val(true);
                    this.form.append($(input));
                } else {
                    draftEl.val(true);
                }

                let parsleyForm = this.form.parsley();
                parsleyForm.destroy();
                this.form.submit();
            };

            this.navigate = (n, showEvenIfInvalid = false) => {
                var that = this;

                // Hide the current tab:
                // let form = $('#' + '{{ form_id }}');

                this.form.parsley().whenValidate({
                    group: 'block-' + that.currentTab
                }).done(function () {
                    // $("#validated-" + that.currentTab).val("True");
                    that.tabValidationState[that.currentTab].state = "valid";
                    that.previousTab = n-1;
                    that.currentTab = n;
                    // Otherwise, display the correct tab:
                    that.showTab(that.currentTab);
                }).fail(function () {
                    // $("#validated-" + that.currentTab).val("False");
                    that.tabValidationState[that.currentTab].state = "invalid";
                    if (showEvenIfInvalid){
                        that.previousTab = n-1;
                        that.currentTab = n;
                        // Otherwise, display the correct tab:
                        that.showTab(that.currentTab);
                    }

                });
            };

            this.updateStepIndicator = () => {
                var that = this;
                // This function removes the "active" class of all steps...
                $(".application-nav__list-item").each((idx, x) => {
                    if (idx === that.currentTab) {
                        x.className = "application-nav__list-item application-nav__list-item--active";
                    }
                    else {
                        if (that.tabValidationState[idx].state === "valid") {
                            x.className = "application-nav__list-item application-nav__list-item--done";
                        } else if (that.tabValidationState[idx].state === "invalid") {
                            x.className = "application-nav__list-item application-nav__list-item--invalid";
                        }
                        else {
                            x.className = "application-nav__list-item";
                        }
                    }
                });
                //... and adds the "active" class to the current step:

                $("#page_link-" + this.currentTab).className = "page_link";
            };

            this.fixStepIndicator = (n) => {
                // This function removes the "active" class of all steps...
                this.jq(".application-nav__list-item").each((idx, x) => {
                    let hiddenField = $("#validated-" + idx);
                    if (idx === n) {
                        x.className = "application-nav__list-item application-nav__list-item--active";
                    }
                    else {
                        if (hiddenField.val() === "True") {
                            x.className = "application-nav__list-item application-nav__list-item--done";
                        } else if (hiddenField.val() === "False") {
                            x.className = "application-nav__list-item application-nav__list-item--invalid";
                        }
                        else {
                            x.className = "application-nav__list-item";
                        }
                    }
                });
                //... and adds the "active" class to the current step:

                this.jq("#page_link-" + n).className = "page_link";
            };

            this.usePaginationMenu = () => {
                var that = this;
                this.jq('[id^="page_link-"]').each((i, x) => {
                    $(x).on("click", () => {
                        if (that.context === "public" && $("#validated-" + i).val() === '') {
                            //dev only!
                            //navigate(i);
                            return false;
                        } else {
                            that.navigate(i, true);
                        }
                    });
                });
            };

            this.prepareSections = () => {
                var that = this;

                this.sections.each((idx, section) => {
                    $(section).find("input, select").each((i, input) => {
                        $(input).attr('data-parsley-group', 'block-' + idx);
                    });

                    //if (idx < that.sections.length){
                    //    let hiddenInputs = $("[name='validated']");
                    //    $(hiddenInputs[idx]).attr('id', 'validated-' + idx);
                    //}
                });

                this.jq('[id^="page_link-"]').each((i, menu) =>  {
                    $(menu).className = "page_link--disabled";
                });
            };

            this.manage_review_checkboxes = () => {
                if (this.jq("#reviewed").checked) {
                    this.form_validated() ? this.jq("#submitBtn").show() : this.jq("#submitBtn").hide()
                }
            };

            // construct
            this.init();
        }
    }
});

window.Parsley.addValidator("requiredIf", {
    validateString : function(value, requirement, parsleyInstance) {
        let field = parsleyInstance.$element.attr("data-parsley-required-if-field");
        if ($('[name="' + field + '"]').filter(':checked').val() === requirement){
            return !!value;
        }
        return true;
    },
    messages: {
        en: 'This field is required, because you answered "%s" to the previous question.'
    },
    priority: 33
});

window.Parsley.addValidator("requiredvalue", {
    validateString : function(value, requirement) {
        return (value === requirement);
    },
    messages: {
        en: 'DOAJ only indexed open access journals which comply with the statement above. Please check and update the open access statement of your journal. You may return to this application at any time.'
    },
    priority: 32
});

window.Parsley.addValidator("optionalIf", {
    validateString : function(value, requirement) {
        theOtherField = $("[name = " + requirement + "]");
        if (!!value || !!($(theOtherField)).val()) {
            $(theOtherField).parsley().reset();
            return true;
        }
        return false;
    },
    messages: {
        en: 'You need to provide the answer to either this field or %s field (or both)'
    },
    priority: 300
});

window.Parsley.addValidator("differentTo", {
    validateString : function(value, requirement) {
      return (!value || ($("[name = " + requirement + "]")).val() !== value)
    },
    messages: {
        en: 'Value of this field and %s field must be different'
    },
    priority: 1
});<commit_msg>fix useStepIndicator method<commit_after>$.extend(doaj, {
    af: {
        active: false,

        newApplicationForm: (params) => {
            return edges.instantiate(doaj.af.ApplicationForm, params);
        },
        ApplicationForm: function(params) {
            this.currentTab = params.hasOwnProperty("currentTab") ? params.currentTab : 0;
            this.previousTab = params.hasOwnProperty("previousTab") ? params.previousTab : 0;

            this.form = $(".application_form");
            this.context = this.form.attr("context");
            this.tabs = $(".tab");
            this.sections = $(".form-section");

            this.tabValidationState = [];

            this.jq = (selector) => {
                return $(selector, this.form);
            };

            this.init = () => {
                this.jq("input, select").each((idx, inp) => {
                    let name = $(inp).attr("name");
                    // console.log(name);
                    if (name) {
                        name = name.split("-");
                        $(inp).attr("data-parsley-errors-container", "#" + name[0] + "_checkbox-errors");
                    }
                });

                let reviewedSelector = this.jq("#reviewed");
                edges.on(reviewedSelector, "click", this, "manage_review_checkboxes");
                // $("#reviewed").on("click", doaj.af.manage_review_checkboxes);

                for (let i = 0; i < this.tabs.length; i++) {
                    this.tabValidationState.push({"state" : "unvalidated"});
                }

                this.prepareSections();
                this.useStepIndicator();

                // Display the current tab
                if (this.context === "admin") {
                    // this.setup_maned();
                }
                // $(".application_form").parsley().validate();
                //this.currentTab = -1;
                //for (let i = 0; i < this.tabs.length; i++) {
                //    this.next();
                    // showTab(i);
                //}
                // this.currentTab = 0;
                this.showTab(this.currentTab);

                let nextSelector = this.jq("#nextBtn");
                let prevSelector = this.jq("#prevBtn");
                let submitSelector = this.jq("#submitBtn");
                let draftSelector = this.jq("#saveDraft");

                edges.on(nextSelector, "click", this, "next");
                edges.on(prevSelector, "click", this, "prev");
                edges.on(submitSelector, "click", this, "submitapplication");
                edges.on(draftSelector, "click", this, "savedraft");
            };

            this.showTab = (n) => {
                // This function will display the specified tab of the form ...
                //hide all other tabs
                // if (n < this.sections.length-1){
                //     let hiddenField = this.jq("#validated-" + n);
                //     if (hiddenField.val() === "") {
                //         hiddenField.val("False");
                //     }
                // }

                this.tabs.each((idx, tab) => {
                    $(tab).hide();
                });

                let submitButton = this.jq("#submitBtn");
                let draftButton = this.jq("#draftBtn");
                $(this.tabs[n]).show();
                this.jq("#cannot_save_draft").hide();
                submitButton.hide();
                draftButton.show();
                // ... and fix the Previous/Next buttons:
                if (n === 0) {
                    this.jq("#prevBtn").hide();
                } else {
                    this.jq("#prevBtn").show();
                }

                if (n === (this.tabs.length - 1)) {
                    //show submit button only if all tabs are validated
                    this.jq("#nextBtn").hide();
                    submitButton.hide();
                    draftButton.show();
                    let validated = this.form_validated();
                    if (!validated) {
                        this.jq("#cannot-submit-invalid-fields").show();
                    } else {
                        this.jq("#cannot-submit-invalid-fields").hide();
                        submitButton.show();
                    }

                } else {
                    let nextBtn = this.jq("#nextBtn");
                    nextBtn.show();
                    nextBtn.html("Next");
                    submitButton.hide();
                    draftButton.show();
                }
                this.currentTab = n;
                this.previousTab = n-1;
                // ... and run a function that displays the correct step indicator:
                if(n === this.tabs.length - 1) {
                    // this.jq("#validated-" + n).val("True");
                    this.prepareReview()
                }
                if (this.context === "admin") {
                    // this.modify_view();
                }
                else if (this.context === "public") {
                    this.updateStepIndicator();
                    // this.fixStepIndicator(n)
                }
                window.scrollTo(0,0);
            };

            this.prepareReview = () => {
                let review_values = $("td[id$='__review_value']");
                review_values.each((idx, question) => {
                    let id = $(question).attr('id');
                    // TODO: think about how to generalise this.  If we add more fields like this or
                    // change the apc_charges bit then it will need updating
                    if (id === "apc_charges__review_value") {
                        let currency = $("select[id$='apc_currency']");
                        let max = $("input[id$='apc_max']");
                        let result = "";
                        let isValid = true;
                        for (let i = 0; i < currency.length; i++){
                            let curr = $(currency[i]).find('option:selected').text();
                            let m = $(max[i]).val();
                            if (m !== "" || curr !== "") {
                                result += (m === "" ? "" : m) + " " + (curr === "" ? "" : curr) + " " + "
";
                            }
                        }
                        if ($(max[0]).parsley().validationResult !== true || ($(currency[0]).parsley().validationResult !== true)) {
                            isValid = false;
                        }
                        if (result === "" && isValid){
                            $(question).parent().hide();
                        }
                        else {
                            $(question).parent().show();
                            $(question).html(result);
                        }
                    }
                    else {
                        let name = id.substring(0, id.indexOf("__review_value"));
                        let input = $("input[name^='" + name + "']");
                        if (input.length === 0) {  //it's not input but select
                            input = $("[name^='" + name + "']");
                            let result = "";
                            input.each((idx, inp) => {
                                let val = $(inp).find('option:selected').text();
                                if (val !== "") {
                                    result += val + "
";
                                }

                            });
                            $(question).html(result);
                        } else {
                            if (id === "keywords__review_value") {
                                let result = "";
                                let this_input = $('#keywords');
                                let keywords = this_input.val().split(",");
                                if (keywords.length !== 1) {
                                    $(keywords).each((idx, kw) => {
                                        result += kw + "
";
                                    });
                                }
                                else {
                                    result = keywords[0];
                                }
                                $(question).html(result);

                            } else {
                                if ($(input).attr("data-parsley-required-if") !== undefined) {
                                    if (input.val() === "" && $(input).parsley().validationResult === true){
                                        $(question).parent().hide();
                                        return;
                                    }
                                    else {
                                        $(question).parent().show();
                                    }
                                }
                                let type = input.attr("type");
                                if (type === "text" || type === "number") {
                                    $(question).html(input.val())
                                } else if (type === "url") {
                                    $(question).html('' + input.val() + '')
                                } else if (type === "radio") {
                                    if (input.is(":checked")) {
                                        let text = $('label[for=' + $(input.filter(':checked')).attr('id') + ']').text();
                                        $(question).html(text);
                                    }
                                } else if (type === "checkbox") {
                                    let result = '';
                                    input.each((idx, i) => {
                                        if ($(i).is(":checked")) {
                                            let text = $('label[for=' + $(i).attr('id') + ']').text();
                                            result += text + "
";
                                        }
                                    });
                                    $(question).html(result)
                                }
                            }
                        }
                    }

                })
            };

            this.form_validated = () => {
                let result = true;
                let inputs = this.jq("[name^='validated']");
                $(inputs).each((idx, input) => {
                    if (idx === inputs.length-1) {
                        return result;
                    }
                    if ($(input).val() !== "True") {
                        result = false;
                        return;
                    }
                });
                return result;
            };

            this.next = () => {
                this.navigate(this.currentTab + 1);
            };

            this.prev = () => {
                this.navigate(this.currentTab - 1, true);
            };

            this.submitaplication = () => {
                let parsleyForm = this.form.parsley();
                this.form.submit();
            };

            this.savedraft = () => {
                this.form.attr('novalidate', 'novalidate');
                var draftEl = $("input[name=draft]");
                if (draftEl.length === 0) {
                    let input = $("<input>")
                       .attr("type", "hidden")
                       .attr("name", "draft").val(true);
                    this.form.append($(input));
                } else {
                    draftEl.val(true);
                }

                let parsleyForm = this.form.parsley();
                parsleyForm.destroy();
                this.form.submit();
            };

            this.navigate = (n, showEvenIfInvalid = false) => {
                var that = this;

                // Hide the current tab:
                // let form = $('#' + '{{ form_id }}');

                this.form.parsley().whenValidate({
                    group: 'block-' + that.currentTab
                }).done(function () {
                    // $("#validated-" + that.currentTab).val("True");
                    that.tabValidationState[that.currentTab].state = "valid";
                    that.previousTab = n-1;
                    that.currentTab = n;
                    // Otherwise, display the correct tab:
                    that.showTab(that.currentTab);
                }).fail(function () {
                    // $("#validated-" + that.currentTab).val("False");
                    that.tabValidationState[that.currentTab].state = "invalid";
                    if (showEvenIfInvalid){
                        that.previousTab = n-1;
                        that.currentTab = n;
                        // Otherwise, display the correct tab:
                        that.showTab(that.currentTab);
                    }

                });
            };

            this.updateStepIndicator = () => {
                $(".application-nav__list-item").each((idx, x) => {
                    if (idx === this.currentTab) {
                        x.className = "application-nav__list-item application-nav__list-item--active";
                    }
                    else {
                        if (this.tabValidationState[idx].state === "valid") {
                            x.className = "application-nav__list-item application-nav__list-item--done";
                        } else if (this.tabValidationState[idx].state === "invalid") {
                            x.className = "application-nav__list-item application-nav__list-item--invalid";
                        }
                        else {
                            x.className = "application-nav__list-item";
                        }
                    }
                });
                //... and adds the "active" class to the current step:

                $("#page_link-" + this.currentTab).className = "page_link";
            };

            this.useStepIndicator = () => {
                $('[id^="page_link-"]').each((i, x) => {
                    $(x).on("click", () => {
                        if (this.context === "public" && this.tabValidationState[i].state === 'unvalidated') {
                            //dev only!
                            //navigate(i);
                            return false;
                        } else {
                            this.navigate(i, true);
                        }
                    });
                });
            };

            this.prepareSections = () => {
                var that = this;

                this.sections.each((idx, section) => {
                    $(section).find("input, select").each((i, input) => {
                        $(input).attr('data-parsley-group', 'block-' + idx);
                    });

                    //if (idx < that.sections.length){
                    //    let hiddenInputs = $("[name='validated']");
                    //    $(hiddenInputs[idx]).attr('id', 'validated-' + idx);
                    //}
                });

                this.jq('[id^="page_link-"]').each((i, menu) =>  {
                    $(menu).className = "page_link--disabled";
                });
            };

            this.manage_review_checkboxes = () => {
                if (this.jq("#reviewed").checked) {
                    this.form_validated() ? this.jq("#submitBtn").show() : this.jq("#submitBtn").hide()
                }
            };

            // construct
            this.init();
        }
    }
});

window.Parsley.addValidator("requiredIf", {
    validateString : function(value, requirement, parsleyInstance) {
        let field = parsleyInstance.$element.attr("data-parsley-required-if-field");
        if ($('[name="' + field + '"]').filter(':checked').val() === requirement){
            return !!value;
        }
        return true;
    },
    messages: {
        en: 'This field is required, because you answered "%s" to the previous question.'
    },
    priority: 33
});

window.Parsley.addValidator("requiredvalue", {
    validateString : function(value, requirement) {
        return (value === requirement);
    },
    messages: {
        en: 'DOAJ only indexed open access journals which comply with the statement above. Please check and update the open access statement of your journal. You may return to this application at any time.'
    },
    priority: 32
});

window.Parsley.addValidator("optionalIf", {
    validateString : function(value, requirement) {
        theOtherField = $("[name = " + requirement + "]");
        if (!!value || !!($(theOtherField)).val()) {
            $(theOtherField).parsley().reset();
            return true;
        }
        return false;
    },
    messages: {
        en: 'You need to provide the answer to either this field or %s field (or both)'
    },
    priority: 300
});

window.Parsley.addValidator("differentTo", {
    validateString : function(value, requirement) {
      return (!value || ($("[name = " + requirement + "]")).val() !== value)
    },
    messages: {
        en: 'Value of this field and %s field must be different'
    },
    priority: 1
});<|endoftext|>


<commit_before>//for now, use memory.
var db = require('levelup')('whatever', { db: require('memdown') });

/**
 * Use ES6 promises
 * @returns {{}}
 */
function defer() {
  var defer = {};
  defer.promise = new Promise(function (resolve, reject) {
    defer.resolve = resolve;
    defer.reject = reject;
    defer.apply = function (err, result) {
      if (err) {
        defer.reject(err);
      } else {
        defer.resolve(result);
      }
    }
  });
  return defer;
}

/**
 *
 * @param {string} key
 * @param {string} value
 * @returns {Promise}
 */
module.exports.put = function (key, value) {
  var deferred = defer();
  db.put(key, value, deferred.apply);
  return deferred.promise;
};

/**
 *
 * @param {string} key
 * @returns {Promise}
 */
module.exports.get = function (key) {
  var deferred = defer();
  db.get(key, deferred.apply);
  return deferred.promise;
};

/**
 *
 * @param {string} key
 * @returns {Promise}
 */
module.exports.del = function (key) {
  var deferred = defer();
  db.del(key, deferred.apply);
  return deferred.promise;
};<commit_msg>use bluebird instead of ES6 promises<commit_after>//for now, use memory.
var db = require('levelup')('whatever', { db: require('memdown') }),
  bluebird = require('bluebird');

/**
 * Use ES6 promises
 * @returns {{}}
 */
function defer() {
  var defer = bluebird.defer();
  defer.apply = function (err, result) {
    if (err) {
      defer.reject(err);
    } else {
      defer.resolve(result);
    }
  };
  return defer;
}

/**
 *
 * @param {string} key
 * @param {string} value
 * @returns {Promise}
 */
module.exports.put = function (key, value) {
  var deferred = defer();
  db.put(key, value, deferred.apply);
  return deferred.promise;
};

/**
 *
 * @param {string} key
 * @returns {Promise}
 */
module.exports.get = function (key) {
  var deferred = defer();
  db.get(key, deferred.apply);
  return deferred.promise;
};

/**
 *
 * @param {string} key
 * @returns {Promise}
 */
module.exports.del = function (key) {
  var deferred = defer();
  db.del(key, deferred.apply);
  return deferred.promise;
};<|endoftext|>


<commit_before>import StringManipulator from 'src/database/stringManipulation';
import exceptions from 'src/database/exceptions';
import constants from 'src/database/constants';
import DateTime from 'src/database/generated-data/dateTime';

const alasql = require('alasql');

const stringManipulator = new StringManipulator();
const dateTime = new DateTime();

function getDataOutOfAlasql(data) {
  return Object.values(data[0][0])[0];
}

function getSecondDataOutOfAlasql(data) {
  return Object.values(data[0][0])[1];
}

function getArray(data) {
  return data[0];
}

function getCurrentFilePath(fileId) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FILE_MANAGER_PATH,
                                                   ' FROM ', constants.ENTITIES_FILE_MANAGER,
                                                   ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                   ' = ', fileId)])
    .then(filePath => resolve(filePath))
    .catch(sqlErr => reject(sqlErr))
  );
}

function getCurrentFolderPath(folderId) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FOLDER_PATH,
                                                   ' FROM ', constants.ENTITIES_FOLDER,
                                                   ' WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' = ', folderId)])
    .then(folderPath => resolve(folderPath))
    .catch(sqlErr => reject(sqlErr))
  );
}

// duplicate private function to help with cascadeChangeFilePath
function changeSingleFilePath(fileId, newPath) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('UPDATE ', constants.ENTITIES_FILE_MANAGER,
                                                   ' SET ', constants.HEADER_FILE_MANAGER_PATH,
                                                   ' = "', newPath,
                                                   '" WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                   ' = ', fileId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function cascadeChangeFilePath(index, prevBasePath, newBasePath, fileArr) {
  return new Promise((resolve, reject) => {
    if (index >= fileArr.length) {
      return true;
    }
    const fileToChangePathIndex = Object.values(fileArr[index])[0];
    let newPath;
    return getCurrentFilePath(fileToChangePathIndex)
    .then((currentFilePath) => {
      const childPath = currentFilePath.toString().split(prevBasePath)[1];
      newPath = stringManipulator.stringConcat(newBasePath, childPath);
      return changeSingleFilePath(fileToChangePathIndex, newPath)
      .catch(sqlErr => reject(sqlErr));
    })
    .then(() => {
      cascadeChangeFilePath(index + 1, prevBasePath, newBasePath, fileArr)
      .catch(err => reject(err));
      resolve();
    })
    .catch(err => reject(err));
  });
}

function changeSingleFolderPath(folderId, newPath) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('UPDATE ', constants.ENTITIES_FOLDER,
                                                   ' SET ', constants.HEADER_FOLDER_PATH,
                                                   ' = "', newPath,
                                                   '" WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' = ', folderId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function changeSingleFolderName(folderId, newFolderName) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('UPDATE ', constants.ENTITIES_FOLDER,
                                                   ' SET ', constants.HEADER_FOLDER_FOLDER_NAME,
                                                   ' = "', newFolderName,
                                                   '" WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' = ', folderId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function cascadeChangeFolderPath(index, prevBasePath, newBasePath, folderArr) {
  return new Promise((resolve, reject) => {
    if (index >= folderArr.length) {
      return true;
    }
    const folderToChangePathIndex = Object.values(folderArr[index])[0];
    let newPath;
    return getCurrentFolderPath(folderToChangePathIndex)
    .then((currentFolderPath) => {
      const childPath = currentFolderPath.toString().split(prevBasePath)[1];
      newPath = stringManipulator.stringConcat(newBasePath, childPath);
      return changeSingleFolderPath(folderToChangePathIndex, newPath)
      .catch(sqlErr => reject(sqlErr));
    })
    .then(() => {
      cascadeChangeFolderPath(index + 1, prevBasePath, newBasePath, folderArr)
      .catch(err => reject(err));
      resolve();
    })
    .catch(err => reject(err));
  });
}

function deleteSingleFolder(folderId) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('DELETE FROM ', constants.ENTITIES_FOLDER,
                                                   ' WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' = ', folderId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function cascadeDeleteFolder(index, folderArr) {
  return new Promise((resolve, reject) => {
    if (index >= folderArr.length) {
      return true;
    }
    const folderToDeleteIndex = Object.values(folderArr[index])[0];
    return deleteSingleFolder(folderToDeleteIndex)
    .then(() => {
      cascadeDeleteFolder(index + 1, folderArr)
      .catch(err => reject(err));
      resolve();
    })
    .catch(err => reject(err));
  });
}

// duplicate private function to help with cascadeDeleteFile
function deleteSingleFile(fileId) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('DELETE FROM ', constants.ENTITIES_FILE_MANAGER,
                                                   ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                   ' = ', fileId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

}

export default function sqlCommands() {
  this.linkDatabaseToIndexedDB = function linkDatabaseToIndexedDB(databaseName) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) => {
        const databaseRequestStr = stringManipulator.stringConcat(
          'CREATE INDEXEDDB DATABASE IF NOT EXISTS ', databaseName, ';',
          'ATTACH INDEXEDDB DATABASE ', databaseName, ';',
          'USE ', databaseName, ';');
        return alasql.promise([databaseRequestStr])
          .then(data => resolve(true))
          .catch(sqlError => reject(sqlError));
      });
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.getFullTableData = function getFullTableData(tableName) {
    // ensure working in browsers that support Promise
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', tableName)])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError)));
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.createTable = function createTable(sqlStatement) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('CREATE TABLE IF NOT EXISTS ', sqlStatement)])
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.insertContent = function insertContent(tableName, alasqlArray) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise(stringManipulator.stringConcat('INSERT INTO ', tableName,
                                                       ' VALUES ?'), alasqlArray)
        .then(data => resolve(data))
        .catch(sqlError => reject(sqlError)));
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.partialSearchFileName = function partialSearchFileName(searchString) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', constants.ENTITIES_FILE_MANAGER,
                                                       ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_NAME,
                                                       ' LIKE "%', searchString, '%"')])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };
  this.getMaxFileId = function getMaxFileId() {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT max(', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                       ') FROM ', constants.ENTITIES_FILE_MANAGER)])
        .then((data) => {
          const maxFileId = getDataOutOfAlasql(data);
          if (typeof maxFileId === 'number') {
            resolve(maxFileId);
          } else {
            resolve(-1);
          }
        }).catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };
  this.getMaxFolderId = function getMaxFolderId() {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT MAX(', constants.HEADER_FOLDER_FOLDER_ID,
                                                       ') FROM ', constants.ENTITIES_FOLDER)])
        .then((data) => {
          const maxFolderId = getDataOutOfAlasql(data);
          if (typeof maxFolderId === 'number') {
            resolve(maxFolderId);
          } else {
            resolve(0);
          }
        }).catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.partialSearchFolderName = function partialSearchFolderName(searchString) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', constants.ENTITIES_FOLDER,
                                                       ' WHERE ', constants.HEADER_FOLDER_FOLDER_NAME,
                                                       ' LIKE "%', searchString, '%"')])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.loadFilesFromFolder = function loadFilesFromFolder(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', constants.ENTITIES_FILE_MANAGER,
                                                       ' WHERE ', constants.HEADER_FILE_MANAGER_FOLDER_ID,
                                                       ' = ', folderId)])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.loadFoldersFromFolder = function loadFoldersFromFolder(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', constants.ENTITIES_FOLDER,
                                                       ' WHERE ', constants.HEADER_FOLDER_PARENT_FOLDER_ID,
                                                       ' = ', folderId)])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.loadFile = function loadFile(fileId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FILE_MANAGER_FILE_MARKDOWN,
                                                       ' FROM ', constants.ENTITIES_FILE_MANAGER,
                                                       ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                       ' = ', fileId)])
        .then(data => resolve(getDataOutOfAlasql(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.saveFile = function saveFile(fileId, markdownFile) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) => {
        .then(() => {
          const currentDateTime = dateTime.getCurrentDateTime();
          alasql.promise([stringManipulator.stringConcat('UPDATE ', constants.ENTITIES_FILE_MANAGER,
                                                         ' SET ', constants.HEADER_FILE_MANAGER_LAST_MODIFIED_DATE,
                                                         ' = "', currentDateTime,
                                                         '" WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                         ' = ', fileId)])
          .catch(sqlError => reject(sqlError));
        })
        .then(() => resolve(true))
        .catch(sqlErr => reject(sqlErr));
      });
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.deleteFile = function deleteFile(fileId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('DELETE FROM ', constants.ENTITIES_FILE_MANAGER,
                                                       ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                       ' = ', fileId)])
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.deleteFolder = function deleteFolder(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('DELETE FROM ', constants.ENTITIES_FOLDER,
                                                       ' WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                       ' = ', folderId)])
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  // external library not functioning so I cannot do anything here
  this.deleteTable = function deleteTable(tableName) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('DROP TABLE IF EXISTS ', tableName)])
        .then(isSuccess => resolve(isSuccess))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };
}
<commit_msg>Add cascadeDeleteFile function to sqlCommands.js<commit_after>import StringManipulator from 'src/database/stringManipulation';
import exceptions from 'src/database/exceptions';
import constants from 'src/database/constants';
import DateTime from 'src/database/generated-data/dateTime';

const alasql = require('alasql');

const stringManipulator = new StringManipulator();
const dateTime = new DateTime();

function getDataOutOfAlasql(data) {
  return Object.values(data[0][0])[0];
}

function getSecondDataOutOfAlasql(data) {
  return Object.values(data[0][0])[1];
}

function getArray(data) {
  return data[0];
}

function getCurrentFilePath(fileId) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FILE_MANAGER_PATH,
                                                   ' FROM ', constants.ENTITIES_FILE_MANAGER,
                                                   ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                   ' = ', fileId)])
    .then(filePath => resolve(filePath))
    .catch(sqlErr => reject(sqlErr))
  );
}

function getCurrentFolderPath(folderId) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FOLDER_PATH,
                                                   ' FROM ', constants.ENTITIES_FOLDER,
                                                   ' WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' = ', folderId)])
    .then(folderPath => resolve(folderPath))
    .catch(sqlErr => reject(sqlErr))
  );
}

// duplicate private function to help with cascadeChangeFilePath
function changeSingleFilePath(fileId, newPath) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('UPDATE ', constants.ENTITIES_FILE_MANAGER,
                                                   ' SET ', constants.HEADER_FILE_MANAGER_PATH,
                                                   ' = "', newPath,
                                                   '" WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                   ' = ', fileId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function cascadeChangeFilePath(index, prevBasePath, newBasePath, fileArr) {
  return new Promise((resolve, reject) => {
    if (index >= fileArr.length) {
      return true;
    }
    const fileToChangePathIndex = Object.values(fileArr[index])[0];
    let newPath;
    return getCurrentFilePath(fileToChangePathIndex)
    .then((currentFilePath) => {
      const childPath = currentFilePath.toString().split(prevBasePath)[1];
      newPath = stringManipulator.stringConcat(newBasePath, childPath);
      return changeSingleFilePath(fileToChangePathIndex, newPath)
      .catch(sqlErr => reject(sqlErr));
    })
    .then(() => {
      cascadeChangeFilePath(index + 1, prevBasePath, newBasePath, fileArr)
      .catch(err => reject(err));
      resolve();
    })
    .catch(err => reject(err));
  });
}

function changeSingleFolderPath(folderId, newPath) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('UPDATE ', constants.ENTITIES_FOLDER,
                                                   ' SET ', constants.HEADER_FOLDER_PATH,
                                                   ' = "', newPath,
                                                   '" WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' = ', folderId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function changeSingleFolderName(folderId, newFolderName) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('UPDATE ', constants.ENTITIES_FOLDER,
                                                   ' SET ', constants.HEADER_FOLDER_FOLDER_NAME,
                                                   ' = "', newFolderName,
                                                   '" WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' = ', folderId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function cascadeChangeFolderPath(index, prevBasePath, newBasePath, folderArr) {
  return new Promise((resolve, reject) => {
    if (index >= folderArr.length) {
      return true;
    }
    const folderToChangePathIndex = Object.values(folderArr[index])[0];
    let newPath;
    return getCurrentFolderPath(folderToChangePathIndex)
    .then((currentFolderPath) => {
      const childPath = currentFolderPath.toString().split(prevBasePath)[1];
      newPath = stringManipulator.stringConcat(newBasePath, childPath);
      return changeSingleFolderPath(folderToChangePathIndex, newPath)
      .catch(sqlErr => reject(sqlErr));
    })
    .then(() => {
      cascadeChangeFolderPath(index + 1, prevBasePath, newBasePath, folderArr)
      .catch(err => reject(err));
      resolve();
    })
    .catch(err => reject(err));
  });
}

function deleteSingleFolder(folderId) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('DELETE FROM ', constants.ENTITIES_FOLDER,
                                                   ' WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                   ' = ', folderId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function cascadeDeleteFolder(index, folderArr) {
  return new Promise((resolve, reject) => {
    if (index >= folderArr.length) {
      return true;
    }
    const folderToDeleteIndex = Object.values(folderArr[index])[0];
    return deleteSingleFolder(folderToDeleteIndex)
    .then(() => {
      cascadeDeleteFolder(index + 1, folderArr)
      .catch(err => reject(err));
      resolve();
    })
    .catch(err => reject(err));
  });
}

// duplicate private function to help with cascadeDeleteFile
function deleteSingleFile(fileId) {
  return new Promise((resolve, reject) =>
    alasql.promise([stringManipulator.stringConcat('DELETE FROM ', constants.ENTITIES_FILE_MANAGER,
                                                   ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                   ' = ', fileId)])
    .then(() => resolve())
    .catch(sqlError => reject(sqlError))
  );
}

function cascadeDeleteFile(index, fileArr) {
  return new Promise((resolve, reject) => {
    if (index >= fileArr.length) {
      return true;
    }
    const fileToDeleteIndex = Object.values(fileArr[index])[0];
    return deleteSingleFile(fileToDeleteIndex)
    .then(() => {
      cascadeDeleteFile(index + 1, fileArr)
      .catch(err => reject(err));
      resolve();
    })
    .catch(err => reject(err));
  });
}

}

export default function sqlCommands() {
  this.linkDatabaseToIndexedDB = function linkDatabaseToIndexedDB(databaseName) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) => {
        const databaseRequestStr = stringManipulator.stringConcat(
          'CREATE INDEXEDDB DATABASE IF NOT EXISTS ', databaseName, ';',
          'ATTACH INDEXEDDB DATABASE ', databaseName, ';',
          'USE ', databaseName, ';');
        return alasql.promise([databaseRequestStr])
          .then(data => resolve(true))
          .catch(sqlError => reject(sqlError));
      });
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.getFullTableData = function getFullTableData(tableName) {
    // ensure working in browsers that support Promise
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', tableName)])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError)));
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.createTable = function createTable(sqlStatement) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('CREATE TABLE IF NOT EXISTS ', sqlStatement)])
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.insertContent = function insertContent(tableName, alasqlArray) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise(stringManipulator.stringConcat('INSERT INTO ', tableName,
                                                       ' VALUES ?'), alasqlArray)
        .then(data => resolve(data))
        .catch(sqlError => reject(sqlError)));
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.partialSearchFileName = function partialSearchFileName(searchString) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', constants.ENTITIES_FILE_MANAGER,
                                                       ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_NAME,
                                                       ' LIKE "%', searchString, '%"')])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };
  this.getMaxFileId = function getMaxFileId() {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT max(', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                       ') FROM ', constants.ENTITIES_FILE_MANAGER)])
        .then((data) => {
          const maxFileId = getDataOutOfAlasql(data);
          if (typeof maxFileId === 'number') {
            resolve(maxFileId);
          } else {
            resolve(-1);
          }
        }).catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };
  this.getMaxFolderId = function getMaxFolderId() {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT MAX(', constants.HEADER_FOLDER_FOLDER_ID,
                                                       ') FROM ', constants.ENTITIES_FOLDER)])
        .then((data) => {
          const maxFolderId = getDataOutOfAlasql(data);
          if (typeof maxFolderId === 'number') {
            resolve(maxFolderId);
          } else {
            resolve(0);
          }
        }).catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.partialSearchFolderName = function partialSearchFolderName(searchString) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', constants.ENTITIES_FOLDER,
                                                       ' WHERE ', constants.HEADER_FOLDER_FOLDER_NAME,
                                                       ' LIKE "%', searchString, '%"')])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.loadFilesFromFolder = function loadFilesFromFolder(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', constants.ENTITIES_FILE_MANAGER,
                                                       ' WHERE ', constants.HEADER_FILE_MANAGER_FOLDER_ID,
                                                       ' = ', folderId)])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.loadFoldersFromFolder = function loadFoldersFromFolder(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT * FROM ', constants.ENTITIES_FOLDER,
                                                       ' WHERE ', constants.HEADER_FOLDER_PARENT_FOLDER_ID,
                                                       ' = ', folderId)])
        .then(data => resolve(getArray(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.loadFile = function loadFile(fileId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('SELECT ', constants.HEADER_FILE_MANAGER_FILE_MARKDOWN,
                                                       ' FROM ', constants.ENTITIES_FILE_MANAGER,
                                                       ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                       ' = ', fileId)])
        .then(data => resolve(getDataOutOfAlasql(data)))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.saveFile = function saveFile(fileId, markdownFile) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) => {
        .then(() => {
          const currentDateTime = dateTime.getCurrentDateTime();
          alasql.promise([stringManipulator.stringConcat('UPDATE ', constants.ENTITIES_FILE_MANAGER,
                                                         ' SET ', constants.HEADER_FILE_MANAGER_LAST_MODIFIED_DATE,
                                                         ' = "', currentDateTime,
                                                         '" WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                         ' = ', fileId)])
          .catch(sqlError => reject(sqlError));
        })
        .then(() => resolve(true))
        .catch(sqlErr => reject(sqlErr));
      });
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.deleteFile = function deleteFile(fileId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('DELETE FROM ', constants.ENTITIES_FILE_MANAGER,
                                                       ' WHERE ', constants.HEADER_FILE_MANAGER_FILE_ID,
                                                       ' = ', fileId)])
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  this.deleteFolder = function deleteFolder(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('DELETE FROM ', constants.ENTITIES_FOLDER,
                                                       ' WHERE ', constants.HEADER_FOLDER_FOLDER_ID,
                                                       ' = ', folderId)])
        .then(data => resolve(true))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };

  // external library not functioning so I cannot do anything here
  this.deleteTable = function deleteTable(tableName) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        alasql.promise([stringManipulator.stringConcat('DROP TABLE IF EXISTS ', tableName)])
        .then(isSuccess => resolve(isSuccess))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  };
}
<|endoftext|>