/**
 * Model for interactiving with the db
 * @author bjora857
 */


/*global storage */

function Transactionhelper() {

    /*
    * To find get a transaction from storage by id
    */
    this.getTransactionFromStorage = function (id) {
        var returner = "-1";
        $(storage.transactions).each(function () {
            if (this.getId() === id) {
                returner = this;
            }
        });

        return returner;
    };

    /*
    * To find update a transaction from storage by id
    */
    this.updateTransactionFromStorage = function (transaction) {
        var returner = false;
        var pos;
        $(storage.transactions).each(function (i) {
            if (this.getId() === transaction.getId()) {
                pos = i;
                returner = true;
            }
        });

        storage.transactions[pos] = transaction;

        return returner;
    };

    /*
   * clean id from prefixed
   */
    this.getCleanId = function (id) {
        return id.substring(2);
    };

    /*
   * Check if we have transactions in storage
   */
    this.checkForValidTransactions = function (transpack) {
        if (transpack.transactions === undefined) {
            return false;
        }
        if (transpack.transactions.length === 0) {
            return false;
        }
        return true;

    };

    /*
   * Update the storage with all transactions available
   */
    this.updateStorage = function (callback) {
        //get all transactions
        var transactionmodel = new Transactionmodel();

        //place them in storage
        var internalCallback = function (data) {

            // if no transactions were fetched
            if (data === - 1) {

                if (transactionview !== undefined) {
                    transactionview.renderNoValidTransactions();
                } else {
                    var transactionview = new Transactionview();
                    transactionview.renderNoValidTransactions();
                }

                return false;
            }
            else {
                storage.transactions = parseJSON(data, "expenses");
                storage.incomes = parseJSON(data, "incomes");
            }
            if (callback !== undefined) {
                callback();
            }
        };

        transactionmodel.getAllTransactions(internalCallback);
    };

}
