class QrCode
  attr_accessor :filename

  def self.build_from_contract_template(contract_template)
    account   = contract_template.project.account
    locale    = I18n.locale
    host      = AppHost.new.domain_with_port
    route     = [:new, account, contract_template.project, contract_template, "#{contract_template.release_type}_release", locale: I18n.locale, host: AppHost.new.domain_with_port]

    url       = Rails.application.routes.url_helpers.url_for(route)
    filename  = [contract_template.project.name, contract_template.name].map(&:parameterize).join("_")

    new(url, filename)
  end

  def initialize(url, filename = "qrcode.png")
    @url = url
    @filename = filename
  end

  def to_png
    Tempfile.new.tap do |file|
      _qr_code.as_png(file: file)
    end
  end

  def to_base64_png(width = 200, height = 200)
    _qr_code.as_png.resize(width, height).to_data_url
  end

  private

  attr_reader :url

  def _qr_code
    @_qr_code ||= RQRCode::QRCode.new(url)
  end
end
