# frozen_string_literal: true

require './lib/kindguardian/utils'

# frozen_string_literal: true

RSpec.describe Kindguardian::Utils do
  describe '#generate_unique_filename_from_url' do
    it 'generates a unique filename from a url' do
      allow(SecureRandom).to receive(:hex).and_return('abcx123')
      expect(described_class.generate_filename_from_url('http://www.teste.com/something.jpg'))
        .to eq 'abcx123-something.jpg'
    end
  end

  describe '#shorten' do
    it 'shortens a string with a defined max length' do
      expect(described_class.shorten('This is a test', 7)).to eq 'This is...'
    end
  end

  describe '#edition_name' do
    context 'if it\'s sunday' do
      it 'it gets The Observer as the edition name' do
        allow(Time).to receive(:now).and_return Time.new(2021, 12, 5)
        expect(described_class.edition_name).to eq 'The Observer'
      end
    end

    context 'if it\'s not sunday' do
      it 'it gets The Guardian as the edition name' do
        allow(Time).to receive(:now).and_return Time.new(2021, 12, 4)
        expect(described_class.edition_name).to eq 'The Guardian'
      end
    end
  end

  describe '#format_index' do
    it 'returns the index correctly formated' do
      expect(described_class.format_index(1)).to eq '001'
      expect(described_class.format_index(123)).to eq '123'
      expect(described_class.format_index(26)).to eq '026'
      expect(described_class.format_index(0)).to eq '000'
    end
  end

  describe '#edition_cover_url' do
    before do
      allow(Date).to receive(:today).and_return Time.new(2021, 12, 5)
    end

    context 'getting a 200 response' do
      it 'fetches the edition cover' do
        expect_any_instance_of(Net::HTTP)
          .to receive(:request)
          .and_return double('response', { code: '200' })
        expect(described_class.edition_cover_url)
          .to eq 'https://img.kiosko.net/2021/12/05/uk/observer.750.jpg'
      end
    end

    context 'getting any other response' do
      it 'return an empty string' do
        expect_any_instance_of(Net::HTTP)
          .to receive(:request)
          .and_return double('response', { code: '404' })
        expect(described_class.edition_cover_url)
          .to be_empty
      end
    end
  end
end
