import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';
import { check } from 'meteor/check';

import { Logger } from 'meteor/ostrio:logger';
import { LoggerFile } from 'meteor/ostrio:loggerfile';
var log = new Logger();
(new LoggerFile(log)).enable();


Meteor.methods({
    'changePass' (username, oldPassword, newPassword) {

        this.unblock();
        Meteor.settings.enableDebug ? log.debug(`changePass() => start change password for username ${username}`, { username, oldPassword, newPassword }) : '';
        check(username, String);
        check(oldPassword, String);
        check(newPassword, String);

        Meteor.settings.enableDebug ? log.debug(`changePass() => find username ${username}`, { username, oldPassword, newPassword }) : '';
        const user = Accounts.findUserByUsername(username);

        if (user == null) {
            Meteor.settings.enableDebug ? log.debug(`changePass() => username not found`, { username, oldPassword, newPassword }) : '';
            throw new Meteor.Error("NotFoundUser");
        }

        // const digestOldPassword = sha256(oldPassword);

        // const password = { digest: digestOldPassword, algorithm: 'sha-256' };

        Meteor.settings.enableDebug ? log.debug(`changePass() => check validation of old password`, { username, oldPassword, newPassword }) : '';
        const result = Accounts._checkPassword(user, oldPassword);

        if (result.error != null) {
            Meteor.settings.enableDebug ? log.debug(`changePass() => validation of old password rejected`, { username, oldPassword, newPassword }) : '';
            throw new Meteor.Error("CheckPassError");
        }


        Accounts.setPassword(user._id, newPassword);
        Meteor.settings.enableDebug ? log.debug(`changePass() => set new password`, { username, oldPassword, newPassword }) : '';
    },
});

Meteor.settings.enableDebug ? log.debug(`endofchangepassword`) : '';