class Contract
  def initialize(releasable, preview = false)
    @releasable = releasable
    @preview = preview
  end

  def to_pdf
    kit = PDFKit.new(as_html)
    kit.to_file("tmp/#{filename}")
  end

  def filename(extension = "pdf")
    "#{@releasable.contract_file_name}.#{extension}"
  end

  def render_attributes
    {
      layout: "contract_pdf",
      locals: { releasable: @releasable, contract_template: contract_template, preview: @preview },
      template: "contracts/pdf", 
    }
  end

  def render_attributes_with_logo
    {
      layout: "contract_pdf",
      locals: { releasable: @releasable, contract_template: contract_template, logo: @releasable.project.account.logo, preview: @preview },
      template: "contracts/pdf", 
    }
  end

  private

  def contract_template
    @releasable.contract_template
  end

  def project
    @releasable.project
  end

  def locale
    @releasable.locale
  end

  def as_html
    I18n.with_locale(locale) do
      if @releasable.project.account.logo.attached?
        ApplicationController.render render_attributes_with_logo
      else
        ApplicationController.render render_attributes
      end
    end
  end
end
