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

  property :state, default: 'active' # active, #closed
  property :needs_help, type: :boolean, default: false
  property :needs_payment, type: :boolean, default: false
  property :closed_at, type: Time
  property :join_request_user_ids, type: Array, default: []
  property :price, type: Float
  property :is_paid, type: :boolean, default: false
  property :paid_at, type: Time
  property :user_requests_closing, type: :boolean, default: false

  has_many :orders, dependent: :destroy
  belongs_to :table
  belongs_to :supplier
  belongs_to :section
  has_and_belongs_to_many :users, storing_keys: true
  has_and_belongs_to_many :employees, storing_keys: true

  attr_protected :supplier_id

  #validates :table_id, presence: true, table can be deleted
  validates :supplier_id, presence: true

  view :by_supplier_id_and_id, key: [:supplier_id, :_id]
  view :for_supplier_view, key: [:supplier_id, :created_at]

  view :active_by_table_id_view, type: :custom, map_function: %|function(doc){
    if(doc.ruby_class == 'List' && doc.state == 'active'){
      emit(doc.table_id, 1);
    }
  }|, reduce_function: '_sum'

  view :active_by_supplier_id_view, type: :custom, map_function: %|function(doc){
    if(doc.ruby_class == 'List' && doc.state == 'active'){
      emit(doc.supplier_id, 1);
    }
  }|, reduce_function: '_sum'

  view :active_by_section_id_view, type: :custom, map_function: %|function(doc){
    if(doc.ruby_class == 'List' && doc.state == 'active' && doc.section_id){
      emit(doc.section_id, 1);
    }
  }|, reduce_function: '_sum'

  view :active_for_supplier_and_section_view, type: :custom, map_function: %[function(doc){
    if(doc.ruby_class == 'List' && doc.state == 'active'){
      emit([doc.supplier_id, doc.section_id], 1);
    }
  }], reduce_function: '_sum'

  view :for_user_view, type: :custom, map_function: %|function(doc){
    if(doc.ruby_class == 'List' && doc.user_ids && doc.user_ids.length){
      doc.user_ids.forEach(function(uid){
        emit([uid, doc.created_at], 1);
      })
    }
  }|, reduce_function: '_sum'

  def self.active
    database.view(active_by_supplier_id_view(reduce: false, include_docs: true))
  end

  # Create, a list given a table and a user
  def self.from_table table, user
    return if user.has_active_list?
    list = new table: table, section_id: table.section_id
    list.supplier_id = table.supplier_id
    list.add_user user
    list.save
    user.active_list_id = list.id
    user.save
    # list_added is depricated, now handled by list_update
    #list.broadcast_supplier list.supplier_id, 'list_added', list.with_info_as_json
    list
  end

  # Create, a list given a table and a employee
  def self.from_table_by_employee table, employee
    unless list = table.active_list
      list = new table: table, section_id: table.section_id
      list.supplier_id = table.supplier_id
      list.add_employee employee
      list.save
    end
    list
  end

  def self.for_supplier(supplier, options = {})
    total_entries = database.view(for_supplier_view({startkey: ["#{supplier.id}\u9999"], endkey: [supplier.id], include_docs: false, reduce: true, descending: true}))
    options[:total_entries] = total_entries
    options[:descending] = true
    with_pagination_options(options) do |options|
      database.view(for_supplier_view({startkey: ["#{supplier.id}\u9999"], endkey: [supplier.id], include_docs: true, reduce: false, descending: true}.merge(options)))
    end
  end

  def self.active_for_supplier(supplier_id, options = {})
    supplier_id = supplier_id.id if supplier_id.is_a?(Supplier)
    database.view(active_by_supplier_id_view(key: supplier_id, reduce: false, include_docs: true))
  end

  def self.active_for_section(section_id, options = {})
    database.view(active_by_section_id_view(key: section_id, reduce: false, include_docs: true))
  end

  # Return all currently active orders for a given section
  def self.active_for_supplier_and_section(supplier, section_id, options = {})
    database.view(active_for_supplier_and_section_view(key: [supplier.id, section_id], reduce: false, include_docs: true))
  end

  def self.active_for_table(table_id, options = {})
    if table_id.is_a?(Array)
      database.view(active_by_table_id_view(options.reverse_merge(keys: table_id, reduce: false, include_docs: true)))
    else
      table_id = table_id.id if table_id.is_a?(SimplyStored::Couch)
      database.view(active_by_table_id_view(options.reverse_merge(key: table_id, reduce: false, include_docs: true)))
    end
  end

  def self.for_user(user, options = {})
    total_entries = database.view(for_user_view({startkey: ["#{user.id}\u9999"], endkey: [user.id], include_docs: false, reduce: true, descending: true}))
    options[:total_entries] = total_entries
    with_pagination_options(options) do |options|
      database.view(for_user_view({startkey: ["#{user.id}\u9999"], endkey: [user.id], include_docs: true, reduce: false, descending: true}.merge(options)))
    end
  end

  def self.for_user_created_at(user, range, options = {})
    database.view(for_user_view({startkey: [user.id, range.last], endkey: [user.id, range.first], include_docs: true, reduce: false, descending: true}.merge(options)))
  end

  def self.for_supplier_created_at(supplier, range, options = {})
    database.view(for_supplier_view({startkey: [supplier.id, range.last], endkey: [supplier.id, range.first], include_docs: true, reduce: false, descending: true}.merge(options)))
  end

  def close!
    orders.include_relation(:product_orders)
    set_price
    orders.map(&:close!)
    self.state = 'closed'
    self.closed_at = Time.now
    if save
      for user in users
        user.active_list_id = nil
        user.save
        broadcast_user user.id, 'list_closed', id: id
      end
      broadcast_supplier supplier_id, 'list_closed', id: id
    end
  end

  def needs_help!
    self.needs_help = true
    if save
      broadcast_users 'list_needs_help', id: id
      broadcast_supplier(supplier_id, 'list_needs_help', id: id)
    end
  end

  def is_helped!
    self.needs_help = false
    if save
      broadcast_users 'list_helped', id: id
      broadcast_supplier supplier_id, 'list_helped', id: id
    end
  end

  def needs_payment!
    self.needs_payment = true
    if save
      broadcast_users 'list_needs_payment', id: id
      broadcast_supplier supplier_id, 'list_needs_payment', id: id
    end
  end

  def is_paid!
    self.is_paid = true
    self.needs_payment = false
    self.paid_at ||= Time.now
    if save
      broadcast_users 'list_is_paid', id: id
      broadcast_supplier supplier_id, 'list_is_paid', id: id
    end
  end

  def user_requests_closing!
    return if user_requests_closing?
    self.user_requests_closing = true
    if save
      broadcast_users 'user_requests_closing', id: id
      broadcast_employees 'user_requests_closing', id: id
      broadcast_supplier supplier_id, 'user_requests_closing', id: id
    end
    #pending
  end


  def move_to_table! to_table
    UserTableMove.create list: self, from_table_id: table_id, to_table: to_table
    from_table_id = self.table_id.try(:dup)
    self.table = to_table
    self.section_id = to_table.section_id
    if save
      # Update the section of an order
      orders.each do |order|
        order.section_id = self.section_id
        order.save
      end
      # user performs a client side refresh
      broadcast_users 'list_changed_table', list_id: id, from_table_id: from_table_id, to_table_id: to_table.id
      broadcast_supplier supplier_id, 'list_changed_table', ListSerializer.new(self).as_json
    end
  end

  def approve_join_request_for_user!(user)
    if join_request_user_ids.include?(user.id)
      join_request_user_ids.delete(user.id)
      user.active_list_id = self.id
      add_user(user)
      user.save
      self.is_dirty
      if save
        broadcast_user user.id, 'join_request_approved', UserUserSerializer.new(user).as_json
      end
    end
  end

  def unlink_user(user)
    changed = join_request_user_ids.delete(user.id)
    changed ||= Array.wrap(user_ids).delete(user.id)
    if user.active_list_id == id
      user.active_list_id = nil
      user.save
    end
    save if changed
  end

  def send_table_join_request_for_user!(requester)
    unless join_request_user_ids.include?(requester.id)
      self.join_request_user_ids << requester.id
      self.is_dirty
      if save
        broadcast_users 'user_join_request', JoinRequestSerializer.new(join_request_for_user(requester)).as_json
      end
    end
  end

  def join_request_for_user(user)
    JoinRequest.new(user: user, list: self)
  end


  def join_requests
    @join_requests ||= join_request_user_ids.any? ? self.class.database.load_document(join_request_user_ids).map{|user| join_request_for_user(user) } : []
  end

  def reject_join_request_for_user!(user_id)
    if join_request_user_ids.include?(user_id)
      join_request_user_ids.delete(user_id)
      self.is_dirty
      if save
        broadcast_user user_id, 'join_request_rejected', id: "jr-#{user_id}"
      end
    end
  end

  def relevant_orders
    orders.reject(&:cancelled?)
  end

  # Store the final list price in a property
  def set_price
    list_total = 0.0
    for order in relevant_orders
      order_total = 0.0
      for product_order in order.product_orders
        order_total += (product_order.quantity * product_order.price).round(2)
      end
      list_total += order_total.round(2)
    end
    self.price = list_total.round(2)
  end

  def table_number
    @table_number ||= table.try(:number).to_i
  end

  def active?
    state == 'active'
  end

  def place_order(products: {}, user: nil, employee: nil)
    return false unless products.any?
    order = Order.create list: self, supplier: supplier, user: user, employee: employee, section_id: section_id, table_id: table_id
    return unless order.id
    orders_placed_count = supplier.increment_orders_placed_count!
    loaded_products = self.class.database.load_document products.keys
    products.each do |product_id, quantity|
      product = loaded_products.find{|p| p.id == product_id} # to get the price
      if quantity.to_i > 0
        ProductOrder.create(order: order, product_id: product_id, quantity: quantity, price: product.price, product_name: product.name)
      end
    end
    set_price
    save


    broadcast_users 'new_order', order: order.with_products_as_json, total_amount: price
    broadcast_users 'orders_placed_count', count: orders_placed_count

    broadcast_supplier supplier.id, 'list_update', active_model_serializer.new(self).as_json
    broadcast_supplier supplier.id, 'new_order', OrderSerializer.new(order)
    broadcast_supplier supplier.id, 'orders_placed_count', count: orders_placed_count
    order
  end

  def as_json(*args)
    super.merge(id: id, table_number: table_number, has_active_orders: has_active_orders? )
  end

  def with_orders_as_json
    return @with_orders_as_json if @with_orders_as_json.present?
    orders.include_relations(product_orders: :product)
    h = as_json
    h[:orders] = []
    h[:list_active] = active?
    list_total = 0.0
    for order in orders
      ho = {products: []}
      ho[:id] = order.id
      ho[:state] = order.state
      order_total = 0.0
      for product_order in order.product_orders
        order_total += (product_order.quantity * product_order.price).round(2)
        ho[:products] << {name: product_order.product_name, id: product_order.product_id, number: product_order.quantity, price: product_order.price}
      end
      ho[:total_amount] = order_total.round(2)
      ho[:state] = order.state
      list_total += ho[:total_amount]
      h[:orders] << ho
    end
    h[:total_amount] = list_total.round(2)
    @with_orders_as_json = h
  end

  def with_orders_and_join_requests_as_json
    return @with_orders_and_join_requests_as_json if @with_orders_and_join_requests_as_json.present?
    @with_orders_and_join_requests_as_json = with_orders_as_json.merge(join_requests_as_json)
  end

  def with_orders_and_join_requests_and_supplier_info_as_json
    with_orders_and_join_requests_as_json.merge(
      supplier_name: supplier.name,
    ).merge(supplier_counter_info)
  end

  def serialized_with_status_join_requests_and_supplier_counters
    as_json.merge(list_active: active? ).merge(join_requests_as_json).merge(supplier_counter_info)
  end

  def supplier_counter_info
    {
      supplier_orders_in_process_count: supplier_orders_in_process_count,
      supplier_orders_placed_count: supplier_orders_placed_count
    }
  end

  def supplier_orders_in_process_count
    Qwaiter::Counter.get(Supplier.orders_in_process_counter_key(supplier_id))
  end

  def supplier_orders_placed_count
    Qwaiter::Counter.get(Supplier.orders_placed_counter_key(supplier_id))
  end

  def has_active_orders?
    Order.count_active_for_supplier_and_list(supplier_id, id) > 0
  end

  def active_orders
    Order.active_for_supplier_and_list(supplier_id, id)
  end

  # Return a join requests object in the form of:
  #   {join_request: [{user_id: '1saf3...', user_email: 'info@qwaiter.com'}, [....]]}
  # DEPRICATED IN EMBER
  def join_requests_as_json
    return @join_requests_as_json if @join_requests_as_json.present?
    h = {join_requests: []}
    # Handle join requests
    if join_request_user_ids.any?
      for user in self.class.database.load_document(join_request_user_ids)
        h[:join_requests] << {user_id: user.id, user_email: user.email}
      end
    end
    @join_requests_as_json = h
  end

  def product_categories
    supplier.product_categories
  end

  def with_info_as_json
    return @with_info_as_json if @with_info_as_json.present?
    hl = as_json
    hl[:total_amount] = orders.inject(0.0){|sum, o| sum + o.product_orders.inject(0.0){|s, po| s + (po.quantity * po.price).round(2)}}.round(2)
    hl[:section_title] = table.section.try(:title)
    @with_info_as_json = hl
  end

  # should not be private, called from order as well
  def broadcast_users(message, content = {})
    for user_id in Array.wrap(user_ids)
      broadcast_user user_id, message, content
    end
  end

  def broadcast_employees(message, content = {})
    #PENDING
  end

end
