extends main
include mixins

block vars

block content
    div(ng-app='allcount', ng-controller='EntityViewController' ng-cloak)
        .container.screen-container(ng-controller='ResetPasswordCtrl')
            +defaultEditForm()(ng-show='doesTokenExists' entity-id='actualEntityId' is-editor='true')
                +defaultFormTemplate()
            .form-group
                button.btn.btn-block.btn-default(lc-tooltip='Submit' ng-click='submitPassword()' ng-show='doesTokenExists')
                    i(class='glyphicon glyphicon-ok')
            .form-group
                p.bg-danger(ng-show='errorMessage') {{errorMessage}}
                p.bg-success(ng-show='successMessage') {{successMessage}}
block js
    +entityJs()
    script.
        angular.module('allcount').controller('ResetPasswordCtrl', ['$scope', 'lcApi', '$q', function ($scope, lcApi, $q) {
            $scope.doesTokenExists = false;
            $scope.successMessage = undefined;
            $scope.errorMessage = undefined;
            $scope.$watch('viewState.formEntityId', function (token) {
                return lcApi.findRange({entityTypeId: 'forgotPassword'}, {
                    filtering: {
                        token: token
                    }
                }).then(function (tokens) {
                    if (tokens && tokens.length > 0) {
                        $scope.doesTokenExists = true;
                        $scope.actualEntityId = tokens[0].id;
                    } else {
                        $scope.errorMessage = 'Token doesn\'t exists or it has been expired'
                        $scope.successMessage = undefined;
                    }
                });
            });
            $scope.submitPassword = function () {
                return $q.when($scope.viewState.editForm.entity()).then(function (entity) {
                    return lcApi.updateEntity({entityTypeId: 'resetPassword'}, entity);
                }).then(function (res) {
                    if (res.username) {
                        $scope.successMessage = 'Password has been successfully changed';
                        $scope.errorMessage = undefined;
                    }
                }, function (err) {
                    $scope.errorMessage = err.data.repeatNewPasswordHash || err;
                    $scope.successMessage = undefined;
                });
            };
        }]);

