class FormSectionGroup extends Directive('hn.enterprise')
    constructor: () ->
        return {
            scope: {
                submit: '&'
            }
            replace: yes
            ### @ngInject ###
            controller: ($scope) ->
                fsg = @

                fsg.currentFormSection = 1
                fsg.callbacks = [null]

                fsg.continue = () ->
                    if fsg.currentFormSection == fsg.numberOfSections
                        fsg.submit()
                    else
                        fsg.currentFormSection++

                fsg.previous = () ->
                    $scope.$evalAsync( () ->
                        fsg.currentFormSection-- if fsg.currentFormSection > 1
                    )

                fsg.changeSection = (num) ->
                    fsg.currentFormSection = num

                fsg.numberOfSections = 0
                fsg.registerSection = (name, callback) ->
                    fsg.numberOfSections++
                    return fsg.numberOfSections

            templateUrl: '/modules/enterprise/components/form_section/form_section_group.html'
            controllerAs: 'fsg'
            bindToController: yes
            transclude: yes
            link: (scope) ->
                scope.form = 'bar'
        }


class FormSection extends Directive('hn.enterprise')
    constructor: (Flash, $compile) ->
        return {
            scope: {
                title: '@'
                name: '@'
            }
            templateUrl: '/modules/enterprise/components/form_section/form_section.html'
            transclude: yes
            replace: yes
            require: '^formSectionGroup'
            link: (scope, element, attrs, formSectionGroupCtrl, transcludeFn) ->

                scope.$parent[scope.name] = scope.formSection

                scope.number = formSectionGroupCtrl.registerSection(scope.name)

                scope.fsg = formSectionGroupCtrl

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

                scope.sectionState = (sectionNumber) ->
                    if formSectionGroupCtrl.currentFormSection == sectionNumber
                        return 'section-active'
                    else if formSectionGroupCtrl.currentFormSection > sectionNumber
                        return 'section-done'
                    else
                        return 'section-future'
        }

class FormSectionPrevious extends Directive('hn.enterprise')
    constructor: () ->
        return {
            require: '^formSectionGroup'
            link: (scope, element, attrs, formSectionCtrl) ->
                element.click(formSectionCtrl.previous)
        }
