class AccountSettingsPage extends Provider('hn.enterprise')
    constructor: (componentProvider, e) ->
        componentProvider.component(this, "AccountSettingsPage", {
            scope: {
            }
            bindToController: yes
            controllerAs: 'vm'
            controller: 'AccountSettingsController'
            templateUrl: "/modules/enterprise/components/account/account_settings.html"
            title: 'Account Settings'
            auth: [e.UserType.BUSINESS, e.UserType.ADMIN]
            resolve:
                ### @ngInject ###
                businessUser: (BusinessUser, Session) ->
                    return BusinessUser.getOne(business_user_id: Session.user.id).$promise
        })

class AccountSettings extends Controller('hn.enterprise')
    constructor: ($scope, $state, $q, $modal, $rootScope, ConfirmModal, $log, Flash, e, Session, User, BusinessUser) ->
        vm = @

        $scope.e = e
        $scope.g = $rootScope.g

        vm.user = $scope.g.user
        vm.interceptStateChange = true

        vm.functionalAreas = e.options('FunctionalArea')

        vm.accountUpdateForm = {
            first_name: vm.user.first_name
            last_name: vm.user.last_name
            title: vm.businessUser.title
            functional_area: vm.user.functional_area
        }


        vm.accountUpdateContainsUnsavedEdits = () ->
            if (vm.accountUpdateForm.first_name != vm.user.first_name \
              or vm.accountUpdateForm.last_name != vm.user.last_name \
              or vm.accountUpdateForm.title != vm.businessUser.title \
              or vm.accountUpdateForm.functional_area != vm.user.functional_area)
                return true
            return false

        vm.submitAccountUpdateForm = (event) ->
            # Submit the update form
            User.updateSelf(vm.accountUpdateForm).$promise.then((user) ->
                Session.reload()
                # This is not pretty, I don't like it, but the Session reload doesn't appear to fully reload the
                # user information internally.
                vm.user.first_name = vm.accountUpdateForm.first_name
                vm.user.last_name = vm.accountUpdateForm.last_name
                vm.user.title = vm.accountUpdateForm.title
                vm.user.functional_area = vm.accountUpdateForm.functional_area
                BusinessUser.getOne(business_user_id: vm.user.id).$promise.then((businessUser) ->
                    vm.businessUser = businessUser
                )
                Flash('Account updated', "success")
            )


        # Cancel account updates
        vm.cancelAccountUpdate = (toState='hn.dashboard') ->
            title = "Would you like to save your changes before leaving?"
            body = "Any unsaved changes will be lost."
            buttons = [
                {
                    "text": "Save"
                    "class": "btn-primary text-uppercase"
                    "click": (closeFn) ->
                        if vm.formValidate($scope.accountUpdateForm)
                            if $scope.accountUpdateForm.$valid
                                vm.submitAccountUpdateForm(event)
                        closeFn()
                        # Cheap for now, just go back to the dashboard.
                        vm.interceptStateChange = false
                        $state.go(toState)
                  },
                {
                    "text": "Don't save"
                    "class": "btn-default text-uppercase"
                    "click": (closeFn) ->
                        closeFn()
                        # Cheap for now, just go back to the dashboard.
                        vm.interceptStateChange = false
                        $state.go(toState)
                }
            ]

            if vm.accountUpdateContainsUnsavedEdits()
                ConfirmModal.newModal(title, body, buttons, $scope.$new())
            else
                vm.interceptStateChange = false
                $state.go(toState)


        # Password stuff - stolen from auth - must be some way to import this.
        vm.data = {}

        vm.validPassword = (password) ->
            #Password must not match your username, must be at least 8 characters long, include at least 1 number, at least 1 uppercase letter, and at least one non-alphanumeric character.
            return password and password.length >=8 and /[0-9A-Z]/.test(password) and password != Session.user.email

        vm.formValidate = (postForm) ->
            if postForm.$invalid and postForm.$submitted
                Flash("Oops! There are errors in the form.
                 Please fix them before continuing.", "error")
                return no
            return yes

        vm.submitChangePasswordForm = () ->
            User.changePassword({}, {current_password: vm.data.oldPassword, password: vm.data.newPassword}).$promise.then((user) ->
                Flash('Success! Password changed', 'success')
                vm.data = {}
                $scope.changePasswordForm.$setPristine()
                $state.go(settings['hn.states.settings'])
            (err) ->
                if err.status = 422
                    msg = "Password must not match your username, must be at least 8 characters long, include at least 1 number, at least 1 uppercase letter, and at least one non-alphanumeric character."
                else
                    msg = 'Oops! Unable to change password, please enter your password and try again'
                Flash(msg, 'error')
            )

        # Show save changes modal on leaving
        $scope.$on('$stateChangeStart', (event, toState, toParams) ->
            if vm.interceptStateChange
                vm.cancelAccountUpdate(toState)
                event.preventDefault()
        )