class EmployeeShift
  include SimplyStored::Couch
  include ActiveModel::SerializerSupport

  property :start_from
  property :end_on
  property :description
  belongs_to :supplier
  belongs_to :employee

  validates :start_from, presence: true
  validates :end_on, presence: true

  view :for_supplier_view, type: :custom, map_function: %|function(doc){
    if(doc.ruby_class == 'EmployeeShift' && doc.start_from && doc.end_on){
      emit([doc.supplier_id, doc.end_on], 1)
    }
  }|, reduce_function: '_sum'

  view :for_employee_view, type: :custom, map_function: %|function(doc){
    if(doc.ruby_class == 'EmployeeShift' && doc.start_from && doc.end_on){
      emit([doc.employee_id, doc.end_on], 1)
    }
  }|, reduce_function: '_sum'

  def self.for_supplier(supplier, relevant_from: 1.week.ago)
    database.view for_supplier_view(startkey: [supplier.id, relevant_from.iso8601], endkey: [supplier.id, {}], reduce: false, include_docs: true)
  end

  def self.for_employee(employee, relevant_from: 1.week.ago)
    database.view for_employee_view(startkey: [employee.id, relevant_from.iso8601], endkey: [employee.id, {}], reduce: false, include_docs: true)
  end
end
