

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var timestamps = require('mongoose-time');
var serverConfig = require('../../config/v16/config');
var messages = require('../../config/v16/messages');
var settings = require('../../config/v16/settings');
var stringify = require('safe-stable-stringify');
var utils = require('../../config/v16/utils');
var denormalize = require('mongoose-filter-denormalize').denormalize;
var ObjectId = mongoose.Schema.ObjectId;
var schemaVersion = serverConfig.config.schemaVersion;
var uniqueValidator = require('mongoose-unique-validator');
var cryptoXor = require('crypto-xor');
var CryptoManager = require('../../server/services/v16/Utils/CryptoManager');
var LoggerMongo = require('../../server/services/v16/Log/LoggerMongo');
var echo = require('../../server/services/v16/Log/LoggerMongo').echo;

var RemoteHostSchema = new mongoose.Schema({
    remote_file: {
        type: String,
        default: ''
    },
    remotehost_denorm_string: {
        type: String
    },
    remoteHost_username: {
        type: String,
        required: true,
        default: ''
    },
    remoteHost_password: {
        type: String,
        required: true,
        default: ''
    },
    userid: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'users',
        default: null
    },
    user_denorm: {
        type: ObjectId,
        ref: 'users',
        default: null,
        autopopulate: true
    },
    __schemaVersion: {
        type: String,
        default: schemaVersion
    }

}).plugin(timestamps());
RemoteHostSchema.plugin(uniqueValidator);

RemoteHostSchema.plugin(require('mongoose-autopopulate'));

function replacer(key, value) {
    if (key == "remotehost_denorm_string") return undefined;else if (key == "gen_id") return undefined;else if (key == "__schemaVersion") return undefined;else return value;
}

RemoteHostSchema.pre('validate', function (next) {
    if (this.userid === undefined || this.userid === null) {
        this.userid = serverConfig.config.DefaultId;
    }
    return next();
});

RemoteHostSchema.pre('update', function (next) {
    var user = this;
    if (this.userid === undefined || this.userid === null) {
        this.userid = serverConfig.config.DefaultId;
    }
    user.user_denorm = user.userid;
    //user.markModified('user_denorm');
    var serializedString = stringify(user, replacer);
    user.remotehost_denorm_string = serializedString;
    //user.markModified('remotehost_denorm_string');
    //user.isNew = true;
    return next();
});

RemoteHostSchema.pre('findOneAndUpdate', async function () {
    var query = this;
    try {
        if (query._update.$set.remoteHost_password) {
            query._update.$set.remoteHost_password = await CryptoManager.EncryptDataAsync(query._update.$set.remoteHost_password);
        }
    } catch (err) {
        LoggerMongo.AddLogs({
            limitString: serverConfig.config.LimitMessageVal, levelStr: "error", message: echo() + "error in RemoteHostSchema's findOneAndUpdate pre hook - " + JSON.stringify(err)
        });
        throw new Error(JSON.stringify(err));
    }
});

RemoteHostSchema.pre('save', async function () {
    var user = this;
    if (this.userid === undefined || this.userid === null) {
        this.userid = serverConfig.config.DefaultId;
    }
    if (this.isModified('remoteHost_password') || this.isNew) {
        try {
            user.remoteHost_password = await CryptoManager.EncryptDataAsync(user.remoteHost_password);
            user.user_denorm = user.userid;
            user.markModified('user_denorm');
            var serializedString = stringify(user, replacer);
            user.remotehost_denorm_string = serializedString;
            user.markModified('remotehost_denorm_string');
            user.isNew = true;
        } catch (err) {
            LoggerMongo.AddLogs({
                limitString: serverConfig.config.LimitMessageVal, levelStr: "error", message: echo() + "error in RemoteHostSchema's save pre hook - " + JSON.stringify(err)
            });
            throw new Error(JSON.stringify(err));
        };
    } else {
        user.user_denorm = user.userid;
        user.markModified('user_denorm');
        var serializedString = stringify(user, replacer);
        user.remotehost_denorm_string = serializedString;
        user.markModified('remotehost_denorm_string');
        user.isNew = true;
    }
});

RemoteHostSchema.methods.GetDecryptedPasswordAsync = async function () {
    try {
        var decryptedPassword = await CryptoManager.DecryptDataAsync(this.remoteHost_password);
        return decryptedPassword;
    } catch (err) {
        LoggerMongo.AddLogs({
            limitString: serverConfig.config.LimitMessageVal, levelStr: "error", message: echo() + "error in password decryption - " + JSON.stringify(err)
        });
        throw JSON.stringify(err);
    }
};

RemoteHostSchema.methods.GetDecryptedPassword = function (callback) {
    CryptoManager.DecryptDataAsync(this.password).then(function (result) {
        callback(null, result);
    }).catch(function (err) {
        callback(err, null);
    });
};

RemoteHostSchema.plugin(uniqueValidator);
var RemoteHost = mongoose.model('remotehosts', RemoteHostSchema);
module.exports = RemoteHost;