import ModalBase from 'ember-cli-dunlop/mixins/modal-base'
import lookupValidator from 'ember-changeset-validations'
import Changeset from 'ember-changeset'
import ModelValidations from 'ember-panda/validations/project-instance'

import get_active_workflow_groups from 'ember-panda/utils/project/active-workflow-groups'
import get_active_workflow_action_definitions from 'ember-panda/utils/project/active-workflow-action-definitions'
import WorkflowActionDefinitionOffsetNodes from 'ember-panda/utils/project/workflow-action-definition-offset-nodes'

export default ModalBase.extend
  dependencies_loading: true
  new_project_instance_groups: Ember.A()
  new_project_instance_actions: Ember.A()
  willOpenModal: ->
    changeset = new Changeset(@get('model'), lookupValidator(ModelValidations), ModelValidations)
    changeset.set 'project_scenario', null # otherwise non null promise object
    @set 'model.changeset', changeset
    @get('model').setProperties #TODO remove me, this is development logic
      client_identifier: 'Ams-AAQ'
      #id: "project-instance-#{@get('globals.modals_counter')}"
    Ember.RSVP.all([
      @get('model.project.workflow_groups')
      @get('model.project.workflow_action_definitions')
    ]).then =>
      @set 'dependencies_loading', false
      @send 'calculate_workflow_based_instances'
  recalculate_workflow_based_instances: Ember.observer 'model.changeset.batch_size', ->
    Ember.run.debounce @, @actions.calculate_workflow_based_instances, 350
  actions:
    calculate_workflow_based_instances: ->
      store = @store
      Ember.run @, ->
        workflow_groups = get_active_workflow_groups @get('model.project.workflow_groups'), @get('model.changeset.project_scenario')
        workflow_action_definitions = get_active_workflow_action_definitions @get('model.project.workflow_action_definitions'), @get('model.changeset.project_scenario')
        project_instance = @get('model')
        project_instance.set 'client_identifier', project_instance.get('changeset.client_identifier') #TODO: REMOVE
        #project = project_instance.get('project')
        #project_instance.get('project_instance_groups').forEach (r) -> r and (r.rollbackAttributes(); r.unloadRecord())
        #project_instance.get('project_instance_groups').invoke 'unloadRecord' #TODO: REMOVE
        #project_instance.get('project_instance_actions').invoke 'unloadRecord' #TODO: REMOVE
        #project_instance.get('project_instance_groups').invoke 'rollbackAttributes'
        #project_instance.get('project_instance_actions').invoke 'rollbackAttributes'
        #@set 'model.project_instance_groups', Ember.A()
        #@set 'model.project_instance_actions', Ember.A()
        # PROJECT GROUPS
        #new_project_instance_groups = []
        @set 'new_project_instance_groups', Ember.A()
        @set 'new_project_instance_actions', Ember.A()
        new_project_instance_groups = @get('new_project_instance_groups')
        new_project_instance_actions = @get('new_project_instance_actions')
        #new_project_instance_groups.invoke 'rollbackAttributes'
        workflow_groups.forEach (workflow_group) ->
          new_project_instance_groups.pushObject store.createRecord 'panda/project-instance-group',
            #id: "#{project_instance.id}-project-instance-group-#{workflow_group.id}-#{Math.round(Math.random()*1000000)}"
            #project_instance: project_instance #IMPORTANT add after close
            workflow_group: workflow_group

        now = moment()
        reference_date = if selected_date = @get('model.changeset.reference_date') then moment(selected_date) else null
        batch_size = @get('model.changeset.batch_size') || 0
        # PROJECT INSTANCES
        if reference_date
          result_nodes = WorkflowActionDefinitionOffsetNodes.create
            workflow_action_definitions: workflow_action_definitions
            reference_date: reference_date
            batch_size: batch_size
          result_nodes.forEach (wrapper) ->
            new_project_instance_action_date = Ember.get(wrapper, 'date')
            project_instance_group = new_project_instance_groups.findBy('workflow_group.id', wrapper.get('record.workflow_group.id'))
            new_project_instance_actions.pushObject store.createRecord 'panda/project-instance-action',
              #id: "#{project_instance.id}-project-instance-action-#{wrapper.get('record_id')}-#{Math.round(Math.random()*1000000)}"
              #project_instance: project_instance
              date: new_project_instance_action_date
              state: if new_project_instance_action_date then (if new_project_instance_action_date.toISOString().substring(0,10) < now.toISOString().substring(0, 10) then 'overdue' else 'planned') else 'pending'
              workflow_action_definition: Ember.get(wrapper, 'record')
              project_instance_group: project_instance_group
        else
          workflow_action_definitions.forEach (workflow_action_definition) ->
            project_instance_group = new_project_instance_groups.findBy('workflow_group.id', workflow_action_definition.get('workflow_group.id'))
            new_project_instance_actions.pushObject store.createRecord 'panda/project-instance-action',
              #id: "#{project_instance.id}-project-instance-action-#{workflow_action_definition.id}-#{Math.round(Math.random()*1000000)}"
              #project_instance: project_instance
              state: 'pending'
              workflow_action_definition: workflow_action_definition
              project_instance_group: project_instance_group
    set_project_scenario: (project_scenario) ->
      @set 'model.changeset.project_scenario', project_scenario
      @set 'model.project_scenario', project_scenario #TODO: REMOVE
      @send 'calculate_workflow_based_instances'
    set_reference_date: (reference_date) ->
      @set 'model.changeset.reference_date', reference_date
      #@set 'model.reference_date', reference_date #TODO: REMOVE
      @send 'calculate_workflow_based_instances'
    close: ->
      project = @get('model.project')
      project_instance = @get('model')
      @get('new_project_instance_groups').forEach (project_instance_group) -> project_instance_group.setProperties project: project, project_instance: project_instance
      @get('new_project_instance_actions').forEach (project_instance_action) -> project_instance_action.setProperties project: project, project_instance: project_instance
      @_super arguments...

    rollback_and_close: ->
      project_instance = @get('model')
      project_instance.get('project_instance_groups').invoke 'rollbackAttributes'
      project_instance.get('project_instance_actions').invoke 'rollbackAttributes'
      project_instance.rollbackAttributes()
      #@get('model.changeset').rollback()
      @send 'close'
    #saveRecord: ->
    #  project = @get('model.project')
    #  component = @
    #  @get('model').save().then (project_instance) ->
    #  #@get('model').save().then (project_instance) ->
    #  #  component.get('new_project_instance_groups').forEach((project_instance_group) ->
    #  #    project_instance_group.setProperties project: project, project_instance: project_instance
    #  #    project_instance_group.save()
    #  #  )
    #  #  component.get('new_project_instance_actions').forEach (project_instance_action) ->
    #  #    project_instance_action.setProperties project: project, project_instance: project_instance
    #  #    project_instance_action.save()
    #  #  component.send 'close'
