class Table
  include SimplyStored::Couch
  include ActiveModel::SerializerSupport
  per_page_method :limit_value #kaminari

  property :number, type: Fixnum, default: 1
  property :position_x, type: Float, default: 0
  property :position_y, type: Float, default: 0
  property :needs_help, type: :boolean, default: false
  property :width, type: Float, default: 0.8
  property :height, type: Float, default: 0.8

  belongs_to :supplier
  belongs_to :section
  has_many :lists

  attr_protected :supplier_id
  attr_accessor :active_list_id, :active_list

  validates :supplier_id, presence: true
  #validates :list_id, presence: true
  validates :number, numericality: true #{greater_than: 0}
  view :by_supplier_id_and_id, key: [:supplier_id, :_id]
  view :by_supplier_id_and_number, key: [:supplier_id, :number]
  view :by_section_id, key: :section_id

  #validates_uniqueness_of :number
  view :by_number, key: :number

  def self.for_supplier(supplier, options = {})
    startkey =  if from_number = options.delete(:from_number).presence
                  [supplier.id, from_number.to_i]
                else
                  [supplier.id]
                end
    endkey =  if to_number = options.delete(:to_number).presence
                [supplier.id, to_number.to_i]
              else
                [supplier.id, {}]
              end

    total_entries = database.view(by_supplier_id_and_number({startkey: startkey, endkey: endkey, include_docs: false, reduce: true}))
    options[:total_entries] = total_entries
    with_pagination_options(options) do |options|
      database.view(by_supplier_id_and_number({startkey: startkey, endkey: endkey, include_docs: true, reduce: false}.merge(options)))
    end
  end

  def serializable_hash
    attributes
  end

  def occupied?
    return @is_occupied if instance_variable_defined?(:'@is_occupied')
    @is_occupied = !self.class.database.view(List.active_view(key: [supplier_id, id], reduce: true)).zero?
  end
  alias occupied occupied?
  def occupied=(val) end

  def self.enrich_active_list_id(tables)
    if tables.is_a?(Array)
      lists = List.active_for_table(tables)
      for table in tables
        if list = lists.find{|l| l.table_id == table.id}
          table.active_list_id = list.id
          table.active_list = list
        end
      end
      tables
    else
      table = tables
      if list = List.active_for_table(table).first
        table.active_list_id = list.id
        table.active_list = list
      end
      table
    end
  end

  def active_list
    # nil memoizing
    return @active_list if @active_list || @active_list_is_set
    self.active_list = self.class.database.view(List.active_view(key: [supplier_id, id], include_docs: true, reduce: false, limit: 1)).try(:first)
  end

  def active_list=(val)
    @active_list_is_set = true
    @active_list = val
  end

  def active_list_id
    @active_list_id || active_list.try(:id)
  end

  def reserved?
    false
  end

  def name
    number
  end
end
