module EasyPatch
  module MemberPatch

    def self.included(base)
      base.send(:include, InstanceMethods)
      base.class_eval do

        belongs_to :group, :foreign_key => 'user_id'

        after_create :copy_mail_notification_from_parent
        before_destroy :remove_watchers

        scope :visible, lambda {|*args|
          user = args.shift || User.current
          user_arel_table = User.arel_table
          if user.admin?
            where(nil)
          else
            # display only members with visible user types and self
            joins(:user, :user => :easy_user_type).where(user_arel_table[:easy_user_type_id].in(user.easy_user_type.try(:easy_user_visible_type_ids)).or(user_arel_table[:id].eq(user.id)))
          end
        }

        scope :sorted_by_importance, -> do
          joins(:user).order('( SELECT MIN(COALESCE( roles.position, 999 )) FROM member_roles INNER JOIN roles ON member_roles.role_id = roles.id WHERE member_roles.member_id = members.id ) DESC', User.fields_for_order_statement)
        end

      end
    end

    module InstanceMethods

      def remove_watchers
        Watcher.joins("JOIN #{Issue.table_name} ON watchable_id = #{Issue.table_name}.id").
          where(watchable_type: 'Issue', user_id: self.user_id).
          where("#{Issue.table_name}.project_id = #{self.project_id}").destroy_all
      end

      def copy_mail_notification_from_parent(parent_id=nil)
        parent_id ||= project.parent.id if project && project.parent
        if parent_id && user
          membership = Member.where(:user_id => user.id, :project_id => parent_id).first
          if membership && membership.mail_notification
            update_attributes(:mail_notification => true)
          end
        end
      end

      def deletable_by_current_user_from?(project)
        return true if User.current.admin?
        r = User.current.highest_role_for_project(project)
        return false if r.nil? || roles.empty?
        r.position <= roles.order(:position => :asc).limit(1).pluck(:position).first.to_i
      end

    end

  end
end
EasyExtensions::PatchManager.register_model_patch 'Member', 'EasyPatch::MemberPatch'
