--
-- FS25 CustomContracts
--
-- @Author: Racc00n
-- @Version: 0.0.1.1
--
-- Register Create invoice dialog

CreateInvoiceDialog = {}
local CreateInvoiceDialog_mt = Class(CreateInvoiceDialog, MessageDialog)
local modDirectory = g_currentModDirectory

function CreateInvoiceDialog.register()
  local dialog = CreateInvoiceDialog.new()
  g_gui:loadGui(modDirectory .. "gui/dialog/invoices/CreateInvoiceDialog.xml", "createInvoiceDialog", dialog)
  CreateInvoiceDialog.INSTANCE = dialog
end

function CreateInvoiceDialog.new(target, custom_mt)
  local dialog = MessageDialog.new(target, custom_mt or CreateInvoiceDialog_mt)

  dialog.invoiceDraft = {
    title = "",
    description = "",
    receiverFarmId = nil,
    lines = {},
    total = 0,
    relatedContractId = nil,
    autoGenerated = false
  }

  return dialog
end

function CreateInvoiceDialog.show(invoiceDraft)
  if CreateInvoiceDialog.INSTANCE == nil then CreateInvoiceDialog.register() end

  local dialog = CreateInvoiceDialog.INSTANCE


  if invoiceDraft ~= nil then
    dialog.invoiceDraft = invoiceDraft
  end

  g_gui:showDialog("createInvoiceDialog")
end

function CreateInvoiceDialog:onCreate()
  CreateInvoiceDialog:superClass().onCreate(self)
  self.linesRenderer = InvoiceLinesRenderer.new()
end

function CreateInvoiceDialog:onGuiSetupFinished()
  CreateInvoiceDialog:superClass().onGuiSetupFinished(self)
end

function CreateInvoiceDialog:onOpen()
  CreateInvoiceDialog:superClass().onOpen(self)

  FocusManager:setFocus(self.titleInput)
  self.titleInput.blockTime = 0
  self.titleInput:onFocusActivate()

  -- Set the invoiceLine smoothlist
  self.invoiceLineTable:setDataSource(self.linesRenderer)
  self.invoiceLineTable:setDelegate(self.linesRenderer)

  -- Retrieve the current farmId
  local myFarmId = g_currentMission:getFarmId()

  -- Setup receiver farm MultiTextOption
  self.receiverFarmIds = {}

  local farmsTexts = {}

  for _, farm in ipairs(g_farmManager.farms) do
    local farmId = farm.farmId
    if farmId ~= FarmManager.SPECTATOR_FARM_ID and farm.showInFarmScreen and farmId ~= myFarmId then
      table.insert(self.receiverFarmIds, farmId)
      table.insert(farmsTexts, farm.name)
    end
  end

  self.receiverSelector:setTexts(farmsTexts)
  self.selectedReceiverFarmIndex = 1
  self.receiverSelector:setState(1, false)

  -- default empty lines if no draft
  if self.invoiceDraft == nil then
    self.linesRenderer:setData({})
  else
    self:applyDraftToUi(self.invoiceDraft)
    self:updateTotalFromLines()
  end

  self.invoiceLineTable:reloadData()
end

function CreateInvoiceDialog:onClose()
  CreateInvoiceDialog:superClass().onClose(self)
end

function CreateInvoiceDialog:onGroupSelectChange(state)
  self.selectedReceiverFarmIndex = state
end

function CreateInvoiceDialog:onRelatedContractSelectChange(state)
  self.selectedRelatedContractIndex = state
end

function CreateInvoiceDialog:onSaveAsDraft(sender)
  if g_client == nil then return end

  local title             = self.titleInput:getText() or ""
  local description       = self.descriptionInput:getText() or ""
  local receiverFarmId    = self.receiverFarmIds[self.selectedReceiverFarmIndex]
  local total             = self:calculateTotalFromDraftLines()
  local creatorFarmId     = g_currentMission:getFarmId()
  local lines             = self.invoiceDraft.lines
  local relatedContractId = self.invoiceDraft.relatedContractId or -1
  local autoGenerated     = self.invoiceDraft.autoGenerated or false

  -- Setup the payload for the new invoice
  local payload           = {
    receiverFarmId = receiverFarmId,
    status = Invoice.STATUS.DRAFT,
    title = title,
    description = description,
    lines = lines,
    total = total,
    relatedContractId = relatedContractId,
    autoGenerated = autoGenerated
  }

  g_client:getServerConnection():sendEvent(CreateInvoiceEvent.new(payload, creatorFarmId))

  self.invoiceDraft = {
    title = "",
    description = "",
    receiverFarmId = nil,
    lines = {},
    total = 0,
    relatedContractId = nil,
    autoGenerated = false
  }

  self:close()
end

function CreateInvoiceDialog:onConfirm(sender)
  if g_client == nil then
    return
  end

  local title             = self.titleInput:getText() or ""
  local description       = self.descriptionInput:getText() or ""
  local receiverFarmId    = self.receiverFarmIds[self.selectedReceiverFarmIndex]
  local total             = self:calculateTotalFromDraftLines()
  local creatorFarmId     = g_currentMission:getFarmId()
  local lines             = self.invoiceDraft.lines
  local relatedContractId = self.invoiceDraft.relatedContractId or -1
  local autoGenerated     = self.invoiceDraft.autoGenerated or false

  local payload           = {
    receiverFarmId = receiverFarmId,
    status = Invoice.STATUS.SENT,
    title = title,
    description = description,
    lines = lines,
    total = total,
    relatedContractId = relatedContractId,
    autoGenerated = autoGenerated
  }

  g_client:getServerConnection():sendEvent(CreateInvoiceEvent.new(payload, creatorFarmId))

  self.invoiceDraft = {
    title = "",
    description = "",
    receiverFarmId = nil,
    lines = {},
    total = 0,
    relatedContractId = nil,
    autoGenerated = false
  }

  self:close()
end

function CreateInvoiceDialog:onCancel(sender)
  self.invoiceDraft = {
    title = "",
    description = "",
    receiverFarmId = nil,
    lines = {},
    total = 0,
    relatedContractId = nil,
    autoGenerated = false
  }
  self:close()
end

function CreateInvoiceDialog:onAddInvoiceLine()
  self:storeUiToDraft()
  self:close()

  AddInvoiceLineDialog.show(self.invoiceDraft)
end

function CreateInvoiceDialog:storeUiToDraft()
  if self.invoiceDraft == nil then return end

  self.invoiceDraft.title = self.titleInput and (self.titleInput:getText() or "") or (self.invoiceDraft.title or "")
  self.invoiceDraft.description = self.descriptionInput and (self.descriptionInput:getText() or "") or
      (self.invoiceDraft.description or "")
  self.invoiceDraft.receiverFarmId = self.receiverFarmIds and self.selectedReceiverFarmIndex and
      self.receiverFarmIds[self.selectedReceiverFarmIndex] or self.invoiceDraft.receiverFarmId
  self.invoiceDraft.total = self:calculateTotalFromDraftLines()
end

function CreateInvoiceDialog:applyDraftToUi(draft)
  if draft == nil then return end

  -- title/description/total
  if self.titleInput ~= nil and draft.title ~= nil then
    self.titleInput:setText(draft.title)
  end
  if self.descriptionInput ~= nil and draft.description ~= nil then
    self.descriptionInput:setText(draft.description)
  end
  if self.totalInput ~= nil and draft.total ~= nil then
    self.totalInput:setText(tostring(draft.total))
  end

  -- receiver selector -> find matching farmId
  if draft.receiverFarmId ~= nil and self.receiverFarmIds ~= nil then
    for i, id in ipairs(self.receiverFarmIds) do
      if id == draft.receiverFarmId then
        self.selectedReceiverFarmIndex = i
        self.receiverSelector:setState(i, false)
        break
      end
    end
  end

  -- if draft.relatedContractId ~= nil and self.relatedContractsIds ~= nil then
  --   for i, id in ipairs(self.relatedContractsIds) do
  --     if id == draft.relatedContractId then
  --       self.selectedRelatedContractIndex = i
  --       if self.relatedContractSelector ~= nil then
  --         self.relatedContractSelector:setState(i, false)
  --       end
  --       break
  --     end
  --   end
  -- end

  -- lines
  self.linesRenderer:setData(draft.lines)
  self:updateTotalFromLines()
end

function CreateInvoiceDialog:calculateTotalFromDraftLines()
  local total = 0

  if self.invoiceDraft ~= nil then
    if #self.invoiceDraft.lines > 0 then
      for _, line in ipairs(self.invoiceDraft.lines) do
        total = total + (tonumber(line.amount) or 0)
      end
    else
      print("No lines")
      return tonumber(self.totalInput:getText())
    end
  end

  return math.floor(total + 0.5)
end

function CreateInvoiceDialog:updateTotalFromLines()
  if self.totalInput == nil then return end
  local total = self:calculateTotalFromDraftLines()
  self.totalInput:setText(tostring(total))
end
