module TestLogging
using Test
using Pia.Logging

@testset "Logging" begin
    @testset "basic" begin
        let buffer = IOBuffer()
            @test Logging.log(1, 2, 3; duplex=buffer) === nothing
            @test length(Logging.Uncategorized.messages) == 1
            seek(buffer, 0)
            @test Logging.Uncategorized.messages[1].message == "1 2 3"
            @test read(buffer, String) == "1 2 3\n"
            
            take!(buffer)
            seek(buffer, 0)
            @test Logging.log(1, 2, 3; duplex=buffer, joiner=", ") === nothing
            @test length(Logging.Uncategorized.messages) == 2
            seek(buffer, 0)
            @test Logging.Uncategorized.messages[2].message == "1, 2, 3"
            @test read(buffer, String) == "1, 2, 3\n"
        end
    end
    
    @testset "custom category" begin
        let cat = LogCategory("TestCategory", nothing)
            @test cat(1, 2, 3) === nothing
            @test Logging.log(cat, 1, 2, 3; joiner=", ") === nothing
            @test length(cat.messages) == 2 && cat.messages[1].message == "1 2 3" && cat.messages[2].message == "1, 2, 3"
        end
        
        let buffer = IOBuffer(), cat = LogCategory("TestCategory", buffer)
            @test cat(1, 2, 3) === nothing
            @test buffer.size > 0
            seek(buffer, 0)
            @test read(buffer, String) == "1 2 3\n"
        end
    end
    
    @testset "purge" begin
        let cat = LogCategory("TestCategory", nothing)
            cat(1, 2, 3)
            @assert length(cat.messages) == 1
            @test empty!(cat) === cat
            @test length(cat.messages) == 0
        end
        
        let cat = LogCategory("TestCategory", nothing)
            cat(1, 2, 3)
            sleep(0.1)
            t0 = time()
            cat(2, 3, 4)
            @assert length(cat.messages) == 2
            @test empty!(cat, older_than=t0) === cat
            @test length(cat.messages) == 1 && cat.messages[1].message == "2 3 4"
        end
    end
end

end # module TestLogging
