require_relative 'concerns/easy_agile_controller_methods'

class EasyKanbanIssuesController < ApplicationController

  include EasyAgileControllerMethods
  self.assignment_class_name = 'EasyKanbanIssue'

  helper :custom_fields

  before_action :find_issue, only: [:update]
  before_action :find_project_by_project_id
  before_action :authorize

  def update
    if params[:easy_kanban_issue].key?(:phase) && (EasyKanbanIssue.not_assigned_phase?(params[:easy_kanban_issue][:phase]))
      @issue.easy_kanban_issue && @issue.easy_kanban_issue.destroy
      head :ok
    else
      begin
        EasyKanbanIssue.transaction do
          @issue.init_journal(User.current)
          @issue.skip_update_associated_agile_relations = true
          @issue.easy_kanban_issue ||= EasyKanbanIssue.new(issue: @issue)
          @issue.easy_kanban_issue.project = @project
          @issue.easy_kanban_issue.phase = params[:easy_kanban_issue].delete(:phase)
          @issue.easy_kanban_issue.position = params[:easy_kanban_issue].delete(:position) || count_position(@issue.easy_kanban_issue, params[:easy_kanban_issue])
          @issue.easy_kanban_issue.save!
          @issue.safe_attributes = params[:easy_kanban_issue]
          @issue.save!
        end
      rescue ActiveRecord::RecordInvalid
        render json: {errors: @issue.errors.full_messages + @issue.easy_kanban_issue.errors.full_messages}, status: :unprocessable_entity
        return
      end

      @positions = EasyKanbanIssue.where(project_id: @project.id, phase: @issue.easy_kanban_issue.phase).order(:position).pluck(:issue_id, :phase, :position)
      @use_workflow = EasySetting.value('easy_agile_use_workflow_on_kanban', @project)
      @possible_phases = EasyKanbanIssue.kanban_phase_for_statuses(@issue, @project, @use_workflow)
      respond_to do |format|
        format.api { render template: 'easy_kanban/data' }
      end
    end
  end

end
