import ModalBase from 'ember-cli-dunlop/mixins/modal-base'
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'
{get} = Ember
export default ModalBase.extend
  loading_message: ''
  finished_message: ''
  willOpenModal: ->
    @set 'loading_message', "Loading project's dependencies"
    @get('model').reload().then => @set 'loading_message', ''
  actions:
    load_instance_list: (file) ->
      component = @
      store = @store
      now = moment()
      @set 'alert_message', ''
      @set 'finished_message', ''
      failure = ((message) ->
        @set 'alert_message', message
        @set 'loading_message', ''
        @set 'finished_message', ''
      ).bind @
      progress_formatter = d3.format('%')
      process_instance_line = ((remaining_lines, current_index, start_length)->
        unless remaining_lines.length
          @set 'alert_message', ''
          @set 'loading_message', ''
          @set 'finished_message', "Finished loading #{start_length} records"
          return
        instance_line = remaining_lines.splice(0, 1)[0]
        current_index += 1
        project = @get('model')
        [identifier, reference_date_spec, scenario_identifier, batch_size] = instance_line.split(/\s*[,;\t]\s*/).map((str) -> str.trim())
        scenario_lookup_attribute = if scenario_identifier.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/) then 'identifier' else 'name'
        batch_size = parseInt(batch_size) || 0
        @set 'loading_message', "Processing #{identifier} #{current_index} / #{start_length} (#{progress_formatter current_index / start_length}) of file #{file.get('name')}"
        selected_scenarios = if scenario = @get('model.project_scenarios').findBy(scenario_lookup_attribute, scenario_identifier) then [scenario] else []
        @set 'selected_project_scenarios', selected_scenarios
        workflow_groups = get_active_workflow_groups @get('model.workflow_groups'), selected_scenarios
        workflow_action_definitions = get_active_workflow_action_definitions @get('model.workflow_action_definitions'), selected_scenarios

        if reference_date_spec
          reference_date = moment(reference_date_spec)
        state = 'uncategorized'
        if scenario
          state = 'unplanned'
        if reference_date_spec
          state = 'planned'
        project_instance = store.createRecord 'panda/project-instance',
          id: identifier
          client_identifier: identifier
          state: state
          reference_date: reference_date
          batch_size: batch_size
          project: project
          project_scenario: selected_scenarios.get('firstObject')

        # PROJECT GROUPS
        new_project_instance_groups = []
        workflow_groups.forEach (workflow_group) ->
          new_project_instance_groups.push store.createRecord 'panda/project-instance-group',
            id: "pig-#{project_instance.id}-#{workflow_group.get('id')}"
            project_instance: project_instance
            workflow_group: workflow_group
            project: project

        # 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 (node) ->
            new_project_instance_action_date = get(node, 'date')
            project_instance_group = new_project_instance_groups.findBy('workflow_group.id', node.get('record.workflow_group.id'))
            store.createRecord 'panda/project-instance-action',
              id: "pia-#{project_instance.id}-#{node.get('record_id')}"
              project_instance: project_instance
              date: new_project_instance_action_date
              state: if new_project_instance_action_date then (if new_project_instance_action_date.isBefore(now) then 'overdue' else 'planned') else 'pending'
              workflow_action_definition: get(node, 'record')
              project_instance_group: project_instance_group
              project: project
        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'))
            store.createRecord 'panda/project-instance-action',
              id: "pia-#{project_instance.id}-#{workflow_action_definition.get('id')}"
              project_instance: project_instance
              state: 'pending'
              workflow_action_definition: workflow_action_definition
              project_instance_group: project_instance_group
              project: project
        process_instance_line(remaining_lines, current_index, start_length)
        #setTimeout (-> process_instance_line(remaining_lines, current_index, start_length)), 2000
      ).bind @
      file_name = String(file.get('name'))
      @set 'loading_message', "Uploading file '#{file_name}'..."
      if file_name.match(/\.xlsx?$/)
        return failure "Cannot upload excel files. Please use comma separated UTF-8 CSV files"
      else unless file_name.match(/\.csv$/)
        return failure "Please use comma separated UTF-8 CSV files"
      file.readAsText().then (result) =>
        #instance_lines = result.split("\n").filter Ember.isPresent
        #instance_lines.splice(0,1) # header
        #process_instance_line instance_lines, 0, instance_lines.length
        #return
        try
          return failure 'File does not have expected header: <b><tt>Batch identifier,Batch date,Scenario,Batch size</tt></b>' unless result.match(/^Batch identifier,Batch date,Scenario,Batch size\n/)
          instance_lines = result.split("\n").filter Ember.isPresent
          instance_lines.splice(0,1) # header
          #setTimeout (-> process_instance_line instance_lines, 0, instance_lines.length), 3000
          process_instance_line instance_lines, 0, instance_lines.length
        catch error
          failure "Cannot load CSV<br>#{error?.message}"
