--
-- FS25 CustomContracts
--
-- @Author: Racc00n
--

CreateInvoiceEvent = {}
local CreateInvoiceEvent_mt = Class(CreateInvoiceEvent, Event)

InitEventClass(CreateInvoiceEvent, "CreateInvoiceEvent")

function CreateInvoiceEvent.emptyNew()
  return Event.new(CreateInvoiceEvent_mt)
end

function CreateInvoiceEvent.new(payload, farmId)
  local self = CreateInvoiceEvent.emptyNew()
  self.payload = payload
  self.farmId = farmId
  return self
end

function CreateInvoiceEvent:writeStream(streamId, connection)
  streamWriteInt32(streamId, self.farmId)
  streamWriteInt32(streamId, self.payload.receiverFarmId or -1)
  streamWriteString(streamId, self.payload.title or "")
  streamWriteString(streamId, self.payload.description or "")

  local lines = self.payload.lines or {}
  streamWriteInt32(streamId, #lines)
  for _, l in ipairs(lines) do
    streamWriteString(streamId, l.title or "")
    streamWriteFloat32(streamId, tonumber(l.amount) or 0)
  end

  streamWriteInt32(streamId, self.payload.total or 0)
  streamWriteInt32(streamId, self.payload.dueAt or 0)
  streamWriteInt32(streamId, self.payload.relatedContractId or -1)
  streamWriteBool(streamId, self.payload.autoGenerated == true)
  streamWriteString(streamId, self.payload.status or Invoice.STATUS.DRAFT)
end

function CreateInvoiceEvent:readStream(streamId, connection)
  local farmId = streamReadInt32(streamId)
  local receiverFarmId = streamReadInt32(streamId)
  local title = streamReadString(streamId)
  local description = streamReadString(streamId)

  local lineCount = streamReadInt32(streamId)
  local lines = {}
  for i = 1, lineCount do
    local t = streamReadString(streamId)
    local a = streamReadFloat32(streamId)
    table.insert(lines, { title = t, amount = a })
  end

  local total = streamReadInt32(streamId)
  local dueAt = streamReadInt32(streamId)
  local relatedContractId = streamReadInt32(streamId)
  local autoGenerated = streamReadBool(streamId)

  local status = streamReadString(streamId)

  self.farmId = farmId
  self.payload = {
    receiverFarmId    = receiverFarmId,
    title             = title,
    description       = description,
    lines             = lines,
    total             = total,
    relatedContractId = relatedContractId,
    autoGenerated     = autoGenerated,
    status            = status
  }

  self:run(connection)
end

function CreateInvoiceEvent:run(connection)
  if not connection:getIsServer() then
    g_server:broadcastEvent(CreateInvoiceEvent.new(self.payload, self.farmId))
  end

  local farmId = self.farmId
  if farmId == nil or farmId == FarmManager.SPECTATOR_FARM_ID then
    return
  end

  local invoiceManager = g_currentMission.CustomContracts.InvoiceManager
  invoiceManager:handleCreateRequest(farmId, self.payload)
end
