# Format for attributes json
attr_format = []
# Format for attributes json
if item.item_attributes.count > 0
  item_attributes = MenuItemAttribute.where(id: item.item_attributes)
  attr_format = item_attributes.group_by {|att| att.attribute_type }.map { |type, values| {type: type, values: values.map(&:name)} }
end

# Format for option json
opt_format = []
# Format for attributes json
if item.item_options.count > 0
  item_options = MenuItemOption.where(id: item.item_options)
  opt_format = item_options.group_by {|opt| opt.option_type }.map { |type, values| {type: type, values: values.map(&:name)} }
end


#Menu Item Information
json.id           item.id
json.code    item.item_code
json.name         item.name
json.alt_name     item.alt_name
json.image        item.image_path.url
json.description  item.description
json.information  item.information
json.type         item.type
json.account_id   item.account_id
json.min_qty      item.min_qty
json.is_available item.is_available
json.is_sub_item  item.is_sub_item
json.unit         item.unit

# Item Sets of Menu Item
json.item_sets item.item_sets do |its|
  json.id                 its.id
  json.name               its.name
  json.alt_name           its.alt_name
  json.min_selectable_qty its.min_selectable_qty
  json.max_selectable_qty its.max_selectable_qty
  json.instances          its.menu_item_instances.map { |i| {id: i.id} }
end

json.attributes attr_format
json.options opt_format
# json.min_selectable_item item.min_selectable_item
# json.max_selectable_item item.max_selectable_item

#Item instance
# if item.menu_item_instances.count == 1 then
#   item_instance = item.menu_item_instances[0]
#   json.price = item_instance.price
#   json.is_available = item_instance.is_available
#   json.is_on_promotion = item_instance.is_on_promotion
#   json.promotion_price = item_instance.promotion_price
#   json.item_attributes = item_instance.item_attributes

json.instances item.menu_item_instances do |is|
  if is.is_available
    # Convert id to name for attributes
    instance_attr = MenuItemAttribute.where(id: item.item_attributes).pluck(:name)

    json.id is.id
    json.code is.item_instance_code
    json.name is.item_instance_name
    json.price is.price
    json.is_available is.is_available
    json.is_default is.is_default
    json.is_on_promotion is.is_on_promotion
    json.promotion_price is.promotion_price
    json.values instance_attr
  end
end

#Child Menu items
# if (item.children) then
#   json.set_items item.children.each do |item|
#     json.partial! 'api/restaurant/menu/menu_item', item: item
#   end
# end
