'use strict';

var UtilArray = require('./UtilArray');
var UtilString = require('../../shared/utils/UtilString');
const { isEqual } = require("lodash/lang");

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

            // exclude systemHeader checking for serverDate, createdDate, createdBy, serverUpdatedDate, serverCreatedDate,
            // currentVersion and versionId - mantis 18242
            const excludeSystemHeaderProperties = ["systemHeader.serverDate", "systemHeader.createdDate", "systemHeader.createdBy",
            "systemHeader.serverUpdatedDate","systemHeader.serverCreatedDate", "systemHeader.currentVersion",
              "systemHeader.versionId", "systemHeader.previousVersionId"];

            if (!excludeSystemHeaderProperties.includes(path)) {

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

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

                    // Old and new updates on the same field ==> conflict
                    if (path === jPath && !isEqual(change.value, jChange.value)) {
                        return true;
                    }

                }
            }
        }
    }
    return false;
}

module.exports = {
    getDiffs: getDiffs,

    checkConflict: checkConflict
};
