class Printer::ReceiptPrinter < Printer::PrinterWorker

  def print_receipt(receipt_no)
    #Use CUPS service
    #Generate PDF
    #Print
    printer = PrintSetting.where("unique_code REGEXP ?", "order.*item.*pdf").first
    pdf = printer.unique_code.constantize.new

    pdf.render_file "tmp/order_item_queue_#{order_id}_#{order_item_id}" + ".pdf"
    #no print in cloud server
    if ENV["SERVER_MODE"] != "cloud"
      self.print("tmp/receipt.pdf")
    end
  end

  def print_receipt_payment_by_card(booking_id)
    #Use CUPS service
    #Generate PDF
    #Print
    filename = "tmp/order_summary_#{booking_id}" + ".pdf"
    printer = PrintSetting.where("unique_code REGEXP ?", "order.*summary.*pdf").first
    pdf = printer.unique_code.constantize.new

    pdf.render_file filename
    #no print in cloud server
    if ENV["SERVER_MODE"] != "cloud"
      self.print(filename)
    end
  end

  def print_receipt_payment_by_account(sale_id)
    #Use CUPS service
    #Generate PDF
    #Print
    printer = PrintSetting.where("unique_code REGEXP ?", "order.*summary.*pdf").first
    filename = "tmp/order_summary_#{booking_id}" + ".pdf"
    pdf = printer.unique_code.constantize.new

    pdf.render_file filename
    #no print in cloud server
    if ENV["SERVER_MODE"] != "cloud"
      self.print(filename)
    end
  end

  def print_receipt_payment_by_vochure(sale_id)
    #Use CUPS service
    #Generate PDF
    #Print
    printer = PrintSetting.where("unique_code REGEXP ?", "order.*summary.*pdf").first
    filename = "tmp/order_summary_#{booking_id}" + ".pdf"
    pdf = printer.unique_code.constantize.new

    pdf.render_file filename
    #no print in cloud server
    if ENV["SERVER_MODE"] != "cloud"
     self.print(filename)
    end
  end

  def print_receipt_payment_by_giftcard(sale_id)
    #Use CUPS service
    #Generate PDF
    #Print
    printer = PrintSetting.where("unique_code REGEXP ?", "order.*summary.*pdf").first
    filename = "tmp/order_summary_#{booking_id}" + ".pdf"
    pdf = printer.unique_code.constantize.new

    pdf.render_file filename
    #no print in cloud server
    if ENV["SERVER_MODE"] != "cloud"
      self.print(filename)
    end
  end

  def print_receipt_payment_by_foc(sale_id)
    #Use CUPS service
    #Generate PDF
    #Print
    printer = PrintSetting.where("unique_code REGEXP ?", "order.*summary.*pdf").first
    filename = "tmp/order_summary_#{booking_id}" + ".pdf"
    pdf = printer.unique_code.constantize.new

    pdf.render_file filename
    #no print in cloud server
    if ENV["SERVER_MODE"] != "cloud"
      self.print(filename)
    end
  end

  #Bill Receipt Print
  def print_receipt_bill(printer_settings, kbz_pay_status, qr_code, cashier_terminal, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info, rebate_amount, shop_details, printed_status, balance, card_data, other_amount, latest_order_no, card_balance_amount, order_reservation = nil, transaction_ref = nil)
    if Lookup.collection_of('print_settings').none? { |x| x == ["ActionCable", "1"] }
      #Use CUPS service
      #Generate PDF
      #Print
      if !printer_settings.unique_code.match?(/receiptbillorder/i)
        if Lookup.collection_of("print_settings").any? { |x| x == ["ReceiptBillA5Pdf", "1"] } #print_settings with name:ReceiptBillA5Pdf
          pdf = ReceiptBillA5Pdf.new(printer_settings, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info, rebate_amount, shop_details, printed_status, balance, card_data, other_amount, latest_order_no, card_balance_amount)
        else
          pdf = PrintSetting.where("unique_code REGEXP ?", "receipt.*bill.*pdf").first.unique_code.constantize.new(printer_settings, kbz_pay_status, qr_code, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info, rebate_amount, shop_details, printed_status, balance, card_data, other_amount, latest_order_no, card_balance_amount, transaction_ref)
        end
      else
        #doemal online order pdf template
        pdf = ReceiptBillOrderPdf.new(printer_settings, sale_items, sale_data, customer_name, item_price_by_accounts, discount_price_by_accounts, member_info, rebate_amount, shop_details,printed_status,balance,card_data,other_amount,latest_order_no,card_balance_amount,order_reservation)
      end

      # print as print copies in printer setting
      count = printer_settings.print_copies

      directory_name = 'public/receipts'
      Dir.mkdir(directory_name) unless File.exists?(directory_name)
      Rails.logger.debug "############## dir::" + directory_name

      filename = "#{directory_name}/receipt_bill_#{sale_data.receipt_no}#{count != 1 ? "_#{count}" : ''}.pdf"
      pdf.render_file filename

      if printed_status != 'Paid' || !Lookup.where(lookup_type: "ReceiptPdfView").pluck(:value).include?('1')
        #no print in cloud server
        if ENV["SERVER_MODE"] != "cloud"
          self.print(filename, cashier_terminal.printer_name)
        end
      end

      Rails.logger.debug "############## filename::" + filename
    else
      if printed_status != 'Paid' || !Lookup.where(lookup_type: "ReceiptPdfView").pluck(:value).include?('1')
        sale_payments = SalePayment
        .select(:payment_method, 'SUM(`sale_payments`.`payment_amount`) AS `payment_amount`')
        .where(sale_id: sale_data.sale_id).group(:payment_method)

        ActionCable.server.broadcast("print_channel_#{Shop.current_shop.shop_code}",
          queue: cashier_terminal.printer_name,
          unique_code: print_settings.unique_code,
          print_copies: print_settings.print_copies,
          data: {
            shop_details: shop_details.as_json,
            body: { sale_data: sale_data,
              booking: sale_data.bookings,
              dining_facility: sale_data.booking.dining_facility.as_json(methods: :type),
              sale_taxes: sale_data.sale_taxes,
              latest_order_no: latest_order_no,
              sale_items: sale_items,
              precision: print_settings.precision,
              delimiter:  print_settings.delimiter,
              member_info: member_info,
              customer_name: customer_name,
              rebate_amount: rebate_amount,
              current_balance: balance,
              card_data: card_data,
              card_balance_amount: card_balance_amount,
              discount_price_by_accounts: discount_price_by_accounts,
              item_price_by_accounts: item_price_by_accounts,
              sale_payments: sale_payments.as_json
            },
            footer: {
              printed_status: printed_status, footer_text: "Thank You! See you Again"
            }
          }
        )
      end
    end

    return filename || '', sale_data.receipt_no, cashier_terminal.printer_name
  end

   # stock check
   def print_stock_check_result(print_settings, stockcheck, stockcheck_items, checker_name, shop_details)
     stock_items= []
     if stockcheck_items.length > 0
       stockcheck_items.each do |sc|
         stock_item= {
           count: sc.stock_count.to_s,
           item_name: MenuItemInstance.get_item_name(sc.item_code)
         }
         stock_items.push(stock_item)
       end
     end

     if Lookup.collection_of('print_settings').none? { |x| x == ["ActionCable", "1"] }
      pdf = StockCheckPdf.new(print_settings,stockcheck, stockcheck_items,checker_name, shop_details)

      pdf.render_file "tmp/print_stock_check_result.pdf"
      #no print in cloud server
      if ENV["SERVER_MODE"] != "cloud"
        self.print("tmp/print_stock_check_result.pdf")
      end
    else
      ActionCable.server.broadcast("print_channel_#{Shop.current_shop.shop_code}",
        queue: print_settings.printer_name,
        unique_code: print_settings.unique_code,
        print_copies: print_settings.print_copies,
        data: {
          stockcheck: stockcheck,
          stockcheck_items: stock_items,
          checker_name: checker_name,
          shop_details: shop_details,
        }
      )
    end
   end

  #Queue No Print
  def print_queue_no(printer_settings,queue)
    #Use CUPS service
    #Generate PDF
    #Print
    pdf = QueueNoPdf.new(printer_settings,queue)
    pdf.render_file "tmp/print_queue_no.pdf"
    #no print in cloud server
    if ENV["SERVER_MODE"] != "cloud"
      self.print("tmp/print_queue_no.pdf")
    end
  end

  #Move Table Print
  def print_move_table(printer_settings, to, from, shop_detail, date, type, moved_by, order_items, oqs)
    if Lookup.collection_of('print_settings').none? { |x| x == ["ActionCable", "1"] }
      #Use CUPS service
      #Generate PDF
      #Print
      pdf = MoveTablePdf.new(printer_settings, to, from, shop_detail, date, type, moved_by, order_items)
      pdf.render_file "tmp/print_move_table.pdf"

      if ENV["SERVER_MODE"] != "cloud"
        if oqs.print_copy
          self.print("tmp/print_move_table.pdf",oqs.printer_name)
        else
          print_settings.print_copies = 1
          print_settings.save!
          #no print in cloud server
          self.print("tmp/print_move_table.pdf", oqs.printer_name)
        end
      end
    else
      ActionCable.server.broadcast("print_channel_#{Shop.current_shop.shop_code}",
        queue: oqs.station_name,
        unique_code: print_settings.unique_code,
        print_copies: print_settings.print_copies,
        data: {
          type: type,
          body: {
            to: to,
            from: from,
            date: date,
            moved_by: moved_by,
            order_items: order_items.as_json,
          },
        }
      )
    end
  end

  #Bill Receipt Print
  def print_crm_order(booking,order_items,setting)
    #Use CUPS service
    #Generate PDF
    #Print
    pdf = CrmOrderPdf.new(booking,order_items,setting)
    pdf.render_file "tmp/print_crm_order.pdf"
    #no print in cloud server
    if ENV["SERVER_MODE"] != "cloud"
      self.print("tmp/print_crm_order.pdf")
    end
  end

  #Queue No Print
  def print_call_waiter(printer_settings,table,time,shop_detail)
    if Lookup.collection_of('print_settings').none? { |x| x == ["ActionCable", "1"] }
      #Use CUPS service
      #Generate PDF
      #Print
      pdf = CallWaiterPdf.new(printer_settings,table,time,shop_detail)

      pdf.render_file "tmp/print_call_waiter.pdf"
      #no print in cloud server
      if ENV["SERVER_MODE"] != "cloud"
        self.print("tmp/print_call_waiter.pdf")
      end
    else
      ActionCable.server.broadcast("print_channel_#{Shop.current_shop.shop_code}",
        queue: print_settings.printer_name,
        unique_code: print_settings.unique_code,
        print_copies: print_settings.print_copies,
        data: {
          shop_name: shop_detail.name,
          name: print_settings.name,
          table: table.name,
          time: time,
        }
      )
    end
  end

  #print receipt pdf from js
  def print_receipt_pdf(filename,receipt_no,print_copies,printer_name)
    count = print_copies.to_i
    # if count == 0
    #   self.print(filename, printer_name)
    # else
    if count == 1
      #no print in cloud server
      if ENV["SERVER_MODE"] != "cloud"
        self.print(filename, printer_name)
      end
    else
      filename = "public/receipts/receipt_bill_#{receipt_no}_#{count}.pdf"
      # no print in cloud server
      if ENV["SERVER_MODE"] != "cloud"
        self.print(filename, printer_name)
      end
    end
    # end
  end

end
