OpenCreateInvoiceDialogEvent = {}
local OpenCreateInvoiceDialogEvent_mt = Class(OpenCreateInvoiceDialogEvent, Event)

InitEventClass(OpenCreateInvoiceDialogEvent, "OpenCreateInvoiceDialogEvent")

function OpenCreateInvoiceDialogEvent.emptyNew()
  return Event.new(OpenCreateInvoiceDialogEvent_mt)
end

function OpenCreateInvoiceDialogEvent.new(draft)
  local self = OpenCreateInvoiceDialogEvent.emptyNew()
  self.draft = draft
  return self
end

function OpenCreateInvoiceDialogEvent:writeStream(streamId, connection)
  -- write your draft fields
  streamWriteInt32(streamId, self.draft.receiverFarmId or 0)
  streamWriteString(streamId, self.draft.title or "")
  streamWriteString(streamId, self.draft.description or "")
  streamWriteInt32(streamId, self.draft.relatedContractId or 0)
  streamWriteBool(streamId, self.draft.autoGenerated == true)

  local lines = self.draft.lines or {}
  streamWriteUInt8(streamId, #lines)
  for _, l in ipairs(lines) do
    streamWriteString(streamId, l.title or "")
    streamWriteInt32(streamId, l.amount or 1)
  end
end

function OpenCreateInvoiceDialogEvent:readStream(streamId, connection)
  self.draft = {}
  self.draft.receiverFarmId = streamReadInt32(streamId)
  self.draft.title = streamReadString(streamId)
  self.draft.description = streamReadString(streamId)
  self.draft.relatedContractId = streamReadInt32(streamId)
  self.draft.autoGenerated = streamReadBool(streamId)

  local n = streamReadUInt8(streamId)
  self.draft.lines = {}
  for i = 1, n do
    table.insert(self.draft.lines, {
      title = streamReadString(streamId),
      amount = streamReadInt32(streamId),
    })
  end

  self:run(connection)
end

function OpenCreateInvoiceDialogEvent:run(connection)
  CreateInvoiceDialog.show(self.draft)
end
