class Menu < ApplicationRecord

  require 'spreadsheet'
  has_many :menu_categories, dependent: :destroy

  validates_presence_of :name, :valid_days, :valid_time_from, :valid_time_to
  # validates_format_of :valid_days, :with => /\A([0-7]{1}(,[0-7]{1})*)?\Z/i
  #Default Scope to pull the active version only
  default_scope { order("created_at asc") }
  scope :active, -> {where("is_active = true")}

  def self.current_menu
    today = DateTime.now
    day_of_week = today.wday
    menus = Menu.where("is_active = true and '#{today.strftime("%H:%M")}' between TIME(valid_time_from) and TIME(valid_time_to)")
    current_menu = nil

    #Loop through the menu which is valid days - get the first menu out and return result
    menus.each do |menu|
      if menu.valid_days.include?(day_of_week.to_s)
        current_menu = menu
        break
      end
    end

    return current_menu
  end

  def self.destroyMenu(menu)
      cats = MenuCategory.where("menu_id=?",menu.id)
      cats.each do |cat|
        abc = MenuCategory.destroyCategory(cat)
      end 
      menu.destroy
      return false
  end

  def self.to_csv
    m_attributes = %w{name is_active valid_days valid_time_from valid_time_to created_by created_at updated_at}    
    CSV.generate(headers: true, row_sep: "\r\n") do |csv|
      csv << m_attributes
      menu = Menu.all
      menu.each do |user|
        csv << m_attributes.map{ |attr| user.send(attr)}
      end
    end
  end

  def self.import(file, created_by) 
    status = ""   
    spreadsheet = open_spreadsheet(file)
    if spreadsheet.sheets.count > 1
      sheet_count = spreadsheet.sheets.count-1
      for i in 0..sheet_count do
        header      = spreadsheet.sheet(i).row(1)
        sheet_name = spreadsheet.sheets[i]

        (2..spreadsheet.sheet(i).last_row).each do |ii|
          row = Hash[[header,spreadsheet.sheet(i).row(ii)].transpose]
          if sheet_name == "Account"
             # Account.create(id:row["id"], title: row["title"],account_type: row["account_type"],discount: row["discount"],point: row["point"],bonus: row["bonus"],rebate: row["rebate"])
             account = Account.find_by_id(row["id"]) 
            if account
              Account.create(title: row["title"],account_type: row["account_type"],discount: row["discount"],point: row["point"],bonus: row["bonus"],rebate: row["rebate"])
            else
              Account.create(id:row["id"], title: row["title"],account_type: row["account_type"],discount: row["discount"],point: row["point"],bonus: row["bonus"],rebate: row["rebate"])
            end
          elsif sheet_name == "Item Set"
             # ItemSet.create(id:row["id"], name: row[name], alt_name: row[alt_name], min_selectable_qty: row[min_selectable_qty], max_selectable_qty: row[max_selectable_qty])
             item_set = ItemSet.find_by_id(row["id"]) 
            if item_set
              ItemSet.create( name: row["name"], alt_name: row["alt_name"], min_selectable_qty: row["min_selectable_qty"], max_selectable_qty: row["max_selectable_qty"])
            else
              ItemSet.create(id:row["id"], name: row["name"], alt_name: row["alt_name"], min_selectable_qty: row["min_selectable_qty"], max_selectable_qty: row["max_selectable_qty"])
            end
          elsif sheet_name == "Menu Item Options"
             # MenuItemOption.create(id:row["id"], option_type: row["option_type"],name: row["name"],value: row["value"])
             item_options = MenuItemOption.find_by_id(row["id"])
            if item_options
              MenuItemOption.create( option_type: row["option_type"],name: row["name"],value: row["value"])
            else
              MenuItemOption.create(id:row["id"], option_type: row["option_type"],name: row["name"],value: row["value"])
            end
          elsif sheet_name == "Menu Item Attributes"
             # MenuItemAttribute.create(id:row["id"], attribute_type: row["attribute_type"],name: row["name"],value: row["value"])
             item_attributes = MenuItemAttribute.find_by_id(row["id"])
            if item_attributes
              MenuItemAttribute.create( attribute_type: row["attribute_type"],name: row["name"],value: row["value"])
            else
              MenuItemAttribute.create(id:row["id"], attribute_type: row["attribute_type"],name: row["name"],value: row["value"])
            end
          elsif sheet_name == "Menu"
            menu = Menu.find_by_id(row["id"])
            if menu
              Menu.create(name: row["name"], is_active: row["is_active"], is_ordering: row["is_ordering"], valid_days: row["valid_days"],valid_time_from: row["valid_time_from"], valid_time_to: row["valid_time_to"], created_by: row["created_by"])
            else
              Menu.create(id:row["id"], name: row["name"], is_active: row["is_active"], is_ordering: row["is_ordering"], valid_days: row["valid_days"],valid_time_from: row["valid_time_from"], valid_time_to: row["valid_time_to"], created_by: row["created_by"])
            end
          elsif sheet_name == "Menu Category"
             # MenuCategory.create(id:row["id"], menu_id: row["menu_id"], code: row["code"], name: row["name"], alt_name: row["alt_name"], order_by: row["order_by"], created_by: row["created_by"], menu_category_id: row["menu_category_id"], is_available: row["is_available"])
             menu_category = MenuCategory.find_by_id(row["id"])
            if menu_category
              MenuCategory.create(menu_id: row["menu_id"], code: row["code"], name: row["name"], alt_name: row["alt_name"], order_by: row["order_by"], created_by: row["created_by"], menu_category_id: row["menu_category_id"], is_available: row["is_available"])
            else
              MenuCategory.create(id:row["id"], menu_id: row["menu_id"], code: row["code"], name: row["name"], alt_name: row["alt_name"], order_by: row["order_by"], created_by: row["created_by"], menu_category_id: row["menu_category_id"], is_available: row["is_available"])
            end
          elsif sheet_name == "Menu Item"
             # MenuItem.create(id:row["id"], item_code: row["item_code"], name: row["name"], alt_name: row["alt_name"], image_path: row["image_path"], description: row["description"], information: row["information"], unit: row["unit"], type: row["type"], menu_category_id: row["menu_category_id"], item_attributes: row["item_attributes"], item_options: row["item_options"], account_id: row["account_id"], min_qty: row["min_qty"], taxable: row["taxable"], is_sub_item: row["is_sub_item"], is_available: row["is_available"], created_by: row["created_by"])
             menu_item = MenuItem.find_by_id(row["id"])
            if menu_item
              MenuItem.create(item_code: row["item_code"], name: row["name"], alt_name: row["alt_name"], image_path: row["image_path"], description: row["description"], information: row["information"], unit: row["unit"], type: row["type"], menu_category_id: row["menu_category_id"], item_attributes: JSON.parse(row["item_attributes"]), item_options: JSON.parse(row["item_options"]), account_id: row["account_id"], min_qty: row["min_qty"], taxable: row["taxable"], is_sub_item: row["is_sub_item"], is_available: row["is_available"], created_by: row["created_by"])
            else
              MenuItem.create(id:row["id"], item_code: row["item_code"], name: row["name"], alt_name: row["alt_name"], image_path: row["image_path"], description: row["description"], information: row["information"], unit: row["unit"], type: row["type"], menu_category_id: row["menu_category_id"], item_attributes: JSON.parse(row["item_attributes"]), item_options: JSON.parse(row["item_options"]), account_id: row["account_id"], min_qty: row["min_qty"], taxable: row["taxable"], is_sub_item: row["is_sub_item"], is_available: row["is_available"], created_by: row["created_by"])
            end
          elsif sheet_name == "Menu Item Instance"
             # MenuItemInstance.create(id:row["id"], menu_item_id: row["menu_item_id"].to_i, item_instance_code: row["item_instance_code"], item_instance_name: row["item_instance_name"], item_attributes: row["item_attributes"], price: row["price"], is_on_promotion: row["is_on_promotion"], promotion_price: row["promotion_price"], is_available: row["is_available"], is_default: row["is_default"])
             item_instance = MenuItemInstance.find_by_id(row["id"])
            if item_instance
              MenuItemInstance.create(menu_item_id: row["menu_item_id"].to_i, item_instance_code: row["item_instance_code"], item_instance_name: row["item_instance_name"], item_attributes: JSON.parse(row["item_attributes"]), price: row["price"], is_on_promotion: row["is_on_promotion"], promotion_price: row["promotion_price"], is_available: row["is_available"], is_default: row["is_default"])
            else
              MenuItemInstance.create(id:row["id"], menu_item_id: row["menu_item_id"].to_i, item_instance_code: row["item_instance_code"], item_instance_name: row["item_instance_name"], item_attributes: JSON.parse(row["item_attributes"]), price: row["price"], is_on_promotion: row["is_on_promotion"], promotion_price: row["promotion_price"], is_available: row["is_available"], is_default: row["is_default"])
            end
          elsif sheet_name == "Menu Instance Item Set"
             # MenuInstanceItemSet.create(id:row["id"], item_set_id: row["item_set_id"], menu_item_instance_id: row["menu_item_instance_id"])
             menu_instance_set = MenuInstanceItemSet.find_by_id(row["id"])
            if menu_instance_set
              MenuInstanceItemSet.create(item_set_id: row["item_set_id"], menu_item_instance_id: row["menu_item_instance_id"])
            else
              MenuInstanceItemSet.create(id:row["id"], item_set_id: row["item_set_id"], menu_item_instance_id: row["menu_item_instance_id"])
            end
          elsif sheet_name == "Menu Item Set" 
             # MenuItemSet.create(id:row["id"], item_set_id: row["item_set_id"], menu_item_id: row["menu_item_id"])
             menu_item_set = MenuItemSet.find_by_id(row["id"])
            if menu_item_set
              MenuItemSet.create(item_set_id: row["item_set_id"], menu_item_id: row["menu_item_id"])
            else
              MenuItemSet.create(id:row["id"], item_set_id: row["item_set_id"], menu_item_id: row["menu_item_id"])
            end
          end
        end
      end
    else
      # Menu by Menu Import
      @shop = Shop.first
      shop_code = ""
      if !@shop.nil?
        if @shop.shop_code
          shop_code = @shop.shop_code + "_"
        end
      end

      sheet = spreadsheet.sheet(0) 
      menu = sheet.row(1)[1]
      is_ordering = sheet.row(1)[3]?sheet.row(1)[3]:0

      imported_menu = Menu.create({name: menu, is_active: true, is_ordering: is_ordering, valid_days: "1,2,3,4,5,6,7",valid_time_from: "00:00:00", valid_time_to: "23:59:59", created_by: created_by}) 

      (4..sheet.last_row).each do |ii|             
          row = Hash[[sheet.row(3),sheet.row(ii)].transpose]   
          menu_cat = MenuCategory.find_by_code(row["Category Code"])  
          if !menu_cat
            menu_cat = MenuCategory.create({menu_id: imported_menu.id, code: row["Category Code"], name: row["Category Name"], alt_name: '', order_by: (ii - 3), created_by: created_by, menu_category_id: nil, is_available: 1})          
          end

          # Menu Item Attributes
          item_attrs = []
          if !row["Attributes"].nil?
            attributes = row["Attributes"].split(',')
            attributes.each do |attr|            
              attribute = MenuItemAttribute.find_by_name(attr)
              if attribute.nil?
                attribute = MenuItemAttribute.create({ attribute_type:"any", name: attr.capitalize, value: attr.downcase })
              end
              item_attrs.push(attribute.id)
            end
          end

          # Menu Item Options
          item_opts = []
          if !row["Options"].nil?
          options = row["Options"].split(',')
            options.each do |opt|
              option = MenuItemOption.find_by_name(opt)
              if option.nil?
                option = MenuItemOption.create({ option_type:"any", name: opt.capitalize, value: opt.downcase })
              end
              item_opts.push(option.id)
            end
          end

          menu_itm = MenuItem.find_by_item_code(row["Item Code"]) 
          if !menu_itm
            account = Account.find_by_title(row["Account"])
            if account.nil?
              account = Account.create({title: row["Account"], account_type: "0"})
            end

            image_path = ""
            if row["Image Path"] && row["Image Path"] != ""
              image_path = URI.parse('public/image/menu_images/'+row["Image Path"])
            end
            menu_itm = MenuItem.create(item_code: row["Item Code"], name: row["Item Name"], account_id: account.id, alt_name: row["Item AltName"], image_path: image_path, description: '', information: '', unit: '', type: "SimpleMenuItem", menu_category_id: menu_cat.id, item_attributes: item_attrs, item_options: item_opts, is_sub_item: 0, is_available: 1, created_by: created_by)
          # else
          #   status = status + "Item Code already exists for " + row["Item Name"] + "."
          end

          instance_attr = []
          menu_inst = MenuItemInstance.find_by_item_instance_code(row["Instance Code"]) 
          if !menu_inst
            instance_name = ''
            if !row["Instance Name"].nil? 
              instance_name = row["Instance Name"]
            end

            if !row["Attributes"].nil?
              if !row["Instance Attribute"].nil? 
                attributes = row["Attributes"].split(',')
                instance_attributes = row["Instance Attribute"].split(',')
                attributes.each do |attr|  
                  if attr == instance_attributes[0]
                    ins_attr = MenuItemAttribute.find_by_name(attr)
                    instance_attr.push(ins_attr.id)                  
                  end                          
                end
              end
            end

            is_default = 0
            if !row["Is Default"].nil?
              is_default = row["Is Default"]
            end
            imported_instance = MenuItemInstance.create(menu_item_id: menu_itm.id, item_instance_code: row["Instance Code"], item_instance_name: instance_name, item_attributes: instance_attr, price: row["Price"], is_on_promotion: false, promotion_price: 0, is_available: true, is_default: is_default)
          end
      end        
    end
    # if status == ''
    status="Menu Imported!"
    # end

    return status
  end

  def self.open_spreadsheet(file)
    case File.extname(file.original_filename)
    when ".csv" then Roo::CSV.new(file.path,nil,:ignore)
    when ".xls" then Roo::Excel.new(file.path,nil,:ignore)
    when ".xlsx" then Roo::Excelx.new(file.path,nil,:ignore)
    else raise "Unknown File type: #{original_filename}"
    end
  end

end