'use strict'

Application.Controllers.controller "PlansIndexController", ["$scope", "$rootScope", "$state", '$uibModal', 'Auth', 'dialogs', 'growl', 'plansPromise', 'groupsPromise', 'Subscription', 'Member', 'subscriptionExplicationsPromise', '_t'
, ($scope, $rootScope, $state, $uibModal, Auth, dialogs, growl, plansPromise, groupsPromise, Subscription, Member, subscriptionExplicationsPromise, _t) ->



    ### PUBLIC SCOPE ###

    ## list of groups
    $scope.groups = groupsPromise

    ## default : do not show the group changing form
    ## group ID of the current/selected user
    $scope.group =
        change: false
        id: null

    ## list of plans, classified by group
    $scope.plansClassifiedByGroup = []
    for group in groupsPromise
      groupObj = { id: group.id, name: group.name, plans: [] }
      for plan in plansPromise
        groupObj.plans.push(plan) if plan.group_id == group.id
      $scope.plansClassifiedByGroup.push(groupObj)

    ## user to deal with
    $scope.ctrl =
      member: null
      member_id: null

    ## already subscribed plan of the current user
    $scope.paidPlan = null

    ## plan to subscribe (shopping cart)
    $scope.selectedPlan = null

    ##
    $scope.subscriptionExplicationsAlert = subscriptionExplicationsPromise.setting.value

    ##
    # Callback to deal with the subscription of the user selected in the dropdown list instead of the current user's
    # subscription. (admins only)
    ##
    $scope.updateMember = ->
      $scope.selectedPlan = null
      $scope.paidPlan = null
      $scope.group.id = $scope.ctrl.member.group_id
      $scope.group.change = false



    ##
    # Add the provided plan to the shopping basket
    # @param plan {Object} The plan to subscribe to
    ##
    $scope.selectPlan = (plan) ->
      if $scope.isAuthenticated()
        if $scope.selectedPlan != plan
          $scope.selectedPlan = plan
        else
          $scope.selectedPlan = null
      else
        $scope.login()



    ##
    # Callback to trigger the payment process of the subscription
    ##
    $scope.openSubscribePlanModal = ->
      if $scope.currentUser.role isnt 'admin'
        payByStripe()
      else
        payOnSite()



    ##
    # Return the group object, identified by the ID set in $scope.group.id
    ##
    $scope.getUserGroup = ->
      for group in $scope.groups
        if group.id == $scope.group.id
          return group



    ##
    # Change the group of the current/selected user to the one set in $scope.group.id
    ##
    $scope.selectGroup = ->
      Member.update {id: $scope.ctrl.member.id}, {user: {group_id: $scope.group.id}}, (user) ->
        $scope.ctrl.member = user
        $scope.group.change = false
        if $scope.currentUser.role isnt 'admin'
          $rootScope.currentUser = user
          Auth._currentUser.group_id = user.group_id
          growl.success(_t('your_group_was_successfully_changed'))
        else
          growl.success(_t('the_user_s_group_was_successfully_changed'))
      , (err) ->
        if $scope.currentUser.role isnt 'admin'
          growl.error(_t('an_error_prevented_your_group_from_being_changed'))
        else
          growl.error(_t('an_error_prevented_to_change_the_user_s_group'))
        console.error(err)


    ##
    # Return an enumerable meaninful string for the gender of the provider user
    # @param user {Object} Database user record
    # @return {string} 'male' or 'female'
    ##
    $scope.getGender = (user) ->
      if user and user.profile
        if user.profile.gender == "true" then 'male' else 'female'
      else 'other'



    ### PRIVATE SCOPE ###

    ##
    # Kind of constructor: these actions will be realized first when the controller is loaded
    ##
    initialize = ->
      if $scope.currentUser
        if $scope.currentUser.role isnt 'admin'
          $scope.ctrl.member = $scope.currentUser
          $scope.paidPlan = $scope.currentUser.subscribed_plan
          $scope.group.id = $scope.currentUser.group_id
        else
          Member.query {requested_attributes:'[subscription]'}, (members) ->
            membersNoPlan = []
            angular.forEach members, (v)->
              membersNoPlan.push v unless v.subscribed_plan
            $scope.members = membersNoPlan

      $scope.$on 'devise:new-session', (event, user)->
        $scope.ctrl.member = user


    $scope.isInFuture = (dateTime)->
      if moment().diff(moment(dateTime)) < 0
        true
      else
        false

    ##
    # Open a modal window which trigger the stripe payment process
    ##
    payByStripe = ->
      $uibModal.open
        templateUrl: '<%= asset_path "stripe/payment_modal.html" %>'
        size: 'md'
        resolve:
          selectedPlan: -> $scope.selectedPlan
          member: -> $scope.ctrl.member
        controller: ['$scope', '$uibModalInstance', '$state', 'selectedPlan', 'member', 'Subscription', 'CustomAsset', ($scope, $uibModalInstance, $state, selectedPlan, member, Subscription, CustomAsset) ->
          $scope.amount = selectedPlan.amount
          $scope.selectedPlan = selectedPlan
          # retrieve the CGV
          CustomAsset.get {name: 'cgv-file'}, (cgv) ->
            $scope.cgv = cgv.custom_asset
          $scope.payment = (status, response) ->
            if response.error
              growl.error(response.error.message)
            else
              $scope.attempting = true
              Subscription.save
                subscription:
                  plan_id: selectedPlan.id
                  user_id: member.id
                  card_token: response.id
              , (data, status) -> # success
                $uibModalInstance.close(data)
              , (data, status) -> # failed
                $scope.alerts = []
                $scope.alerts.push({msg: _t('an_error_occured_during_the_payment_process_please_try_again_later'), type: 'danger' })
                $scope.attempting = false
        ]
      .result['finally'](null).then (subscription)->
        $scope.ctrl.member.subscribed_plan = angular.copy($scope.selectedPlan)
        Auth._currentUser.subscribed_plan = angular.copy($scope.selectedPlan)
        $scope.paidPlan = angular.copy($scope.selectedPlan)
        $scope.selectedPlan = null



    ##
    # Open a modal window which trigger the local payment process
    ##
    payOnSite = ->
      $uibModal.open
        templateUrl: '<%= asset_path "plans/payment_modal.html" %>'
        size: 'sm'
        resolve:
          selectedPlan: -> $scope.selectedPlan
          member: -> $scope.ctrl.member
        controller: ['$scope', '$uibModalInstance', '$state', 'selectedPlan', 'member', 'Subscription', ($scope, $uibModalInstance, $state, selectedPlan, member, Subscription) ->
          $scope.plan = selectedPlan
          $scope.member = member
          $scope.ok = ->
            $scope.attempting = true
            Subscription.save
              subscription:
                plan_id: selectedPlan.id
                user_id: member.id
            , (data, status) -> # success
              $uibModalInstance.close(data)
            , (data, status) -> # failed
              $scope.alerts = []
              $scope.alerts.push({msg: _t('an_error_occured_during_the_payment_process_please_try_again_later'), type: 'danger' })
              $scope.attempting = false

          $scope.cancel = ->
            $uibModalInstance.dismiss('cancel')
        ]
      .result['finally'](null).then (reservation)->
        $scope.ctrl.member.subscribed_plan = angular.copy($scope.selectedPlan)
        Auth._currentUser.subscribed_plan = angular.copy($scope.selectedPlan)
        index = $scope.members.indexOf($scope.ctrl.member)
        $scope.members.splice(index, 1)
        $scope.ctrl.member = null
        $scope.paidPlan = angular.copy($scope.selectedPlan)
        $scope.selectedPlan = null



    ## !!! MUST BE CALLED AT THE END of the controller
    initialize()
]
