# typed: false
require "rails_helper"

describe ColorLogger do
  let(:sink) { StringIO.new }
  let(:read_sink) do
    proc do
      sink.rewind
      sink_contents = sink.read
      sink.rewind
      sink.truncate(0)
      sink_contents
    end
  end

  context "created with #make" do
    let(:logger) { ColorLogger.make(sink) }

    it "logs contents with color", quiet: false do
      logger.info("foo")
      expect(read_sink.call).to eq("foo\n")

      line1 = "bar!"
      logger.info(line1)
      line2 = "#{"yes".red}, #{"no".blue}"
      logger.info(line2)

      expect(read_sink.call).to eq(["#{line1}\n", "#{line2}\n"].join(""))
    end

    it "respects the 'quiet' wrapper", quiet: false do
      ColorLogger.quiet { logger.info("don't log me") }
      logger.info("but do log this")
      expect(read_sink.call).to eq("but do log this\n")
    end

    it "by default, rspec logs are quiet" do
      logger.info("don't log me")
      expect(read_sink.call).to eq("")
    end
  end

  # it "uses stdout by default when included" do
  #   inst =
  #     Class
  #       .new do
  #         def self.name
  #           "TestClass"
  #         end
  #         include HasColorLogger
  #       end
  #       .new
  #   expect(inst.logger.sink).to be($stdout)
  # end

  it "can have a sink injected" do
    s = sink
    klass =
      Class.new do
        def self.name
          "TestClass"
        end
        include HasColorLogger[s]
      end
    inst = klass.new

    # quiet by default
    inst.logger.info("don't log")
    expect(read_sink.call).to eq("")

    # unquiet works
    ColorLogger.unquiet do
      inst.logger.info("foo bar")
      expect(read_sink.call).to eq("foo bar\n")

      klass.logger.info("baz quux")
      expect(read_sink.call).to eq("baz quux\n")
    end
  end
end
