module Consultoria
	class Board < ApplicationRecord
	  belongs_to :category, optional: true, foreign_key: 'consultoria_category_id'
	  has_many :lists, foreign_key: 'consultoria_board_id'
	  has_many :cards, through: :lists
	  has_many :taggings, through: :cards
	  has_many :users, through: :cards
	  has_many :user_cards, through: :users
	  has_many :tags, foreign_key: 'consultoria_board_id'
	  has_many :protocols, foreign_key: 'consultoria_board_id'

	  has_and_belongs_to_many :board_users, foreign_key: 'consultoria_board_id', 
                            join_table: 'consultoria_user_boards', 
                            association_foreign_key: "user_id",
							class_name: 'Consultoria::User'
	  acts_as_paranoid
	  scope :for_user, ->(user) { 
		  if user.can_update_company?
			self
		  else
			left_joins(:board_users).where(
			"
				creator_id = :user_id or
				(user_id = :user_id or (is_private is null or is_private = false))
			", user_id: user.to_param
			).group(:id)
		  end
	  }
	  scope :filtered_by_category, ->(category_id){
		  if !category_id.blank?
			where('consultoria_category_id = ?', category_id)
		  else
			self
		  end
	  }
      scope :filtered_by_card_tags, ->(tag_ids){
		  left_outer_joins(:taggings)
		  .where('taggings.tag_id IN (?)', tag_ids)
		}
	  scope :filtered_by_card_users, ->(user_ids){
		  left_outer_joins(:user_cards)
		  .where('user_cards.user_id IN (?)', user_ids)
		}

	  after_save :setup_users_from_cards

	  def setup_users_from_cards
		if self.is_private
			self.board_users.push(self.users)
			Consultoria::UserBoard.clear_duplications
		end
	  end

	  def add_user(user)
		result = self.board_users.push(Consultoria::User.find(user.id))
		Consultoria::UserBoard.clear_duplications

		return result
	  end

	  def remove_user(user)
		result = self.board_users.delete(Consultoria::User.find(user.id))
		

		return result
	  end

	  def duplicate(company_id=nil)
		cloned = self.deep_clone include: [:protocols, :tags, {
			lists: [cards: [
				:user_cards,
				:users,
				:tags,
				checklists: [:tasks],
			]
		] } ], use_dictionary: true

		cloned.title = "#{self.title} clone"
		if company_id
			cloned.company_id = company_id
		end
	    cloned.save
		cloned.cards.remove_dates
		Consultoria::Tagging.clear_duplications
		Consultoria::UserCard.clear_duplications
		cloned.move_cards_to_begin
	  end

	  def duplicate_to_company(company_id)
	  	self.duplicate(company_id)
	  end

	  def toggle_inactive
		self.is_inactive = !self.is_inactive
		self.save
	  end

	  def move_cards_to_begin
		first_list = self.lists.where(status: "scheduled").first
		self.cards.update_all(consultoria_list_id: first_list.id)
	  end

	  def percentages_by_list
		percentages = {}
		total = cards.count.to_f
		lists.each do |list|
			percentages[list.status] = ((list.cards.count.to_f / total) * 100).to_i
		end
		return percentages
	  end
	end
end
