'use strict';

var UtilArray = require('./UtilArray');
var UtilString = require('../../shared/utils/UtilString');

function getDiffs(currentDocument, remoteDocument) {

    var diffs = [];

    var remoteKeys = Object.keys(remoteDocument);
    var currentKeys = Object.keys(currentDocument);
    var unionKeys = UtilArray.union(remoteKeys, currentKeys);

    for (var k = 0; k < unionKeys.length; k++) {
        var key = unionKeys[k];
        if (key !== 'systemHeader') {

            var currentValue = JSON.stringify(currentDocument[key]);
            var remoteValue = JSON.stringify(remoteDocument[key]);

            if (currentValue !== remoteValue) {//compare as string
                diffs.push({
                    fieldName: key,
                    currentValue: currentDocument[key],
                    remoteValue: remoteDocument[key]
                });
            }

        }
    }

    return diffs;
};

function checkConflict(newUpdatesData, oldUpdatesData) {
    if (newUpdatesData && newUpdatesData.updates && oldUpdatesData && oldUpdatesData.updates) {

        for (var i = newUpdatesData.updates.length - 1; i >= 0; i--) {

            var change = newUpdatesData.updates[i];
            var path = UtilString.convertToObjectPath(change.path);

            if (path.indexOf("systemHeader") !== 0) {   // exclude systemHeader checking

                for (var j = oldUpdatesData.updates.length - 1; j >= 0; j--) {

                    var jChange = oldUpdatesData.updates[j];
                    var jPath = UtilString.convertToObjectPath(jChange.path, '/');

                    if (path === jPath) {   // Old and new updates on the same field ==> conflict
                        return true;
                    }

                }
            }
        }
    }
    return false;
}

module.exports = {
    getDiffs: getDiffs,

    checkConflict: checkConflict
};