class Schedule < ActiveRecord::Base
  attr_accessible :owner_id, :name, :applicant_ids, :assistant_ids

  # associations
  belongs_to :owner, class_name: 'User', primary_key: :id, foreign_key: :owner_id
  belongs_to :user
  has_many :schedule_users, dependent: :destroy
  has_many :users, through: :schedule_users, dependent: :destroy
  has_many :events, class_name: 'ScheduleEvent', dependent: :destroy

  # accessors
  attr_accessor :applicant_ids, :assistant_ids

  # validations
  validates :name, :owner_id, presence: true, length: { maximum: 200 }

  # delegates
  delegate :name, :email, :authentication_token, to: :owner, allow_nil: true, prefix: true

  # callbacks
  after_save :update_users

  # FriendlyId
  extend FriendlyId
  friendly_id :name, :use => [:slugged, :history]

  # methods
  def today_events
    events.where(start_at: Date.current.beginning_of_day .. Date.current.end_of_day)
  end

  def load_schedule_user_ids
    self.applicant_ids = schedule_users.select{|s| s.kind == 'applicant'}.map(&:user_id)
    self.assistant_ids = schedule_users.select{|s| s.kind == 'assistant'}.map(&:user_id)
  end

  def update_users
    schedule_users.destroy_all
    permissions_id = Permission.where(subject_class: 'Schedule', action: ['read', 'create']).pluck(:id)
    if applicant_ids.present?
      User.where(id: applicant_ids).each do |applicant|
        schedule_users.create(user_id: applicant.id)
        unless applicant.can?(:manage, Schedule)
          permissions_id.each{|permission_id| PermissionsRole.where(permission_id: permission_id, role_id: applicant.role_id).first_or_create}
        end
      end
    end
    if assistant_ids.present?
      User.where(id: assistant_ids).each do |assistant|
        schedule_users.create(user_id: assistant.id, kind: 'assistant')
        unless assistant.can?(:manage, Schedule)
          permissions_id.each{|permission_id| PermissionsRole.where(permission_id: permission_id, role_id: assistant.role_id).first_or_create}
        end
      end
    end
  end

  def self.for_user current_user
    if current_user.can? :manage, 'all'
      scoped.order('schedules.updated_at DESC')
    else
      scoped.where('schedules.id in (?)', current_user.schedule_ids + Array.wrap(current_user.schedule.try(:id)))
    end
  end

  def permission? current_user
    nil
    if owner_id == current_user.id
      'owner'
    else
      other = schedule_users
      if other.select{|o| o.kind == 'assistant'}.map(&:user_id).include?(current_user.id)
        'assistant'
      elsif other.select{|o| o.kind == 'applicant'}.map(&:user_id).include?(current_user.id) or current_user.can?(:manage, 'all')
        'applicant'
      end
    end
  end

end
