module EasyAgileBoard
  module IssuePatch

    def self.included(base)

      base.class_eval do

        belongs_to :easy_sprint
        has_one :issue_easy_sprint_relation, :dependent => :destroy
        has_one :easy_agile_backlog_relation, :dependent => :destroy
        has_one :easy_kanban_issue, :dependent => :destroy

        before_save :update_associated_easy_agile_backlog_relation
        after_save :create_or_update_agile_associations

        validates :easy_story_points, :numericality => { :only_integer => true, :allow_nil => true }

        attr_accessor :skip_update_associated_agile_relations

        safe_attributes 'easy_sprint_id', 'easy_story_points'

        journalized_options[:format_detail_reflection_columns] << 'easy_sprint_id'

        ##### AGILE 2016

        def kanban_phase
          self.easy_kanban_issue && self.easy_kanban_issue.phase
        end

        def scrum_phase
          self.issue_easy_sprint_relation && self.issue_easy_sprint_relation.relation_type
        end

        #### DEPRECATED

        def easy_agile_rating(sprint_project_id, options = {})
          issue_easy_sprint_relation.easy_agile_rating(options)
        end

        def update_associated_easy_agile_backlog_relation
          self.easy_agile_backlog_relation = nil if closing? && easy_agile_backlog_relation
        end

        def create_or_update_agile_associations
          return true if skip_update_associated_agile_relations

          if self.easy_kanban_issue
            self.easy_kanban_issue.update_from_issue
          end

          if easy_sprint_id_changed?
            children.each { |subtask| subtask.update_attribute(:easy_sprint_id, self.easy_sprint_id) }
          end

          if !self.easy_sprint_id || !self.easy_sprint
            self.issue_easy_sprint_relation.destroy if self.issue_easy_sprint_relation
            return true
          end

          self.build_issue_easy_sprint_relation unless self.issue_easy_sprint_relation
          self.issue_easy_sprint_relation.easy_sprint_id = self.easy_sprint_id
          self.issue_easy_sprint_relation.update_from_issue

          true
        end

      end
    end

  end

end
EasyExtensions::PatchManager.register_model_patch 'Issue', 'EasyAgileBoard::IssuePatch'
