require 'spec_helper'
require 'debci/html_helpers'

describe Debci::HTMLHelpers do
  include Debci::HTMLHelpers
  FakeTest = Struct.new(:trigger, :pin_packages, keyword_init: true) do
    def pinned?
      pin_packages && !pin_packages.empty?
    end
  end

  context 'file_link' do
    it 'returns nil on missing files' do
      expect(file_link(nil, '%s')).to be_nil
    end
    it 'formats 0' do
      expect(file_link(0, '%s')).to eq("0 Bytes")
    end
    it 'formats 1 MB' do
      expect(file_link(1024**2, '%s')).to eq("1 MB")
    end
  end

  let(:test) { FakeTest.new }

  context 'title_test_trigger_pin' do
    it 'returns empty string for no data' do
      expect(title_test_trigger_pin(test)).to eq('')
    end
    it 'adds trigger if any' do
      test.trigger = "foo"
      expect(title_test_trigger_pin(test)).to match("Trigger:\nfoo")
    end
    it 'adds pin_packages if any' do
      test.pin_packages = [["src:rake", "unstable"]]
      expect(title_test_trigger_pin(test)).to eq("Pinned packages:\nsrc:rake from unstable\n")
    end
  end

  context 'expanding pin_packages' do
    it 'expands no pin_packages to nil' do
      expect(expand_pin_packages(test)).to eq([])
    end

    it 'expands pin_packages with one' do
      test.pin_packages = [["src:rake", "unstable"]]
      expect(expand_pin_packages(test)).to eq(["src:rake from unstable"])
    end

    it 'expands pin_packages with multiple' do
      test.pin_packages = [["src:rake,src:ruby", "unstable"]]
      expect(expand_pin_packages(test)).to eq(["src:rake from unstable", "src:ruby from unstable"])
    end

    it 'expands pin_packages entry with multiple packages' do
      test.pin_packages = [["src:rake", "src:ruby", "unstable"]]
      expect(expand_pin_packages(test)).to eq(["src:rake from unstable", "src:ruby from unstable"])
    end

    it 'expands pin_packages with invalid entry' do
      test.pin_packages = [[nil, "unstable"]]
      expect(expand_pin_packages(test)).to be_an(Array)
    end
  end

  context 'handling ANSI escape codes' do
    it 'escapes HTML' do
      expect(ansi_to_html("<span></span>")).to eq("&lt;span&gt;&lt;/span&gt;")
    end

    it 'converts ANSI to HTML' do
      expect(ansi_to_html("\e[0;32m.\e[0m")).to eq("<font color=\"green\">.</font>")
    end

    it 'returns nil untouched' do
      expect(ansi_to_html(nil)).to be_nil
    end

    it 'strips ANSI codes off if anything goes wrong with the conversion' do
      expect(ANSI::BBCode).to receive(:ansi_to_html).and_raise(RuntimeError)
      expect(ansi_to_html("\e[0;31mCRASH")).to eq("CRASH")
    end
  end
end
