#  Copyright (c) 2012-2017, Jungwacht Blauring Schweiz. This file is part of
#  hitobito and licensed under the Affero General Public License version 3
#  or later. See the COPYING file at the top-level directory or at
#  https://github.com/hitobito/hitobito.

class InvoiceDecorator < ApplicationDecorator
  decorates :invoice

  delegate :group_invoice_list_invoice_path, :group_invoice_path, to: :helpers

  def show_path
    if invoice_list
      group_invoice_list_invoice_path(group, invoice_list, model)
    else
      group_invoice_path(group, model)
    end
  end

  def cost
    format_currency(calculated[:cost])
  end

  def vat
    format_currency(calculated[:vat])
  end

  def total
    format_currency(model.total || calculated[:total])
  end

  def amount_open
    format_currency(model.amount_open)
  end

  def amount_paid
    format_currency(model.amount_paid)
  end

  def format_currency(amount)
    ActiveSupport::NumberHelper.number_to_currency(amount, {unit: currency, format: "%n %u"})
  end

  def currency
    model.new_record? ? model.invoice_config.currency : model.currency
  end

  def as_quicksearch
    {id: id, label: label_with_group, type: :invoice, icon: :"file-invoice"}
  end

  def label_with_group
    label = title
    label += " (#{sequence_number})" if sequence_number
    h.safe_join([group.to_s, label], ": ")
  end
end
