package log

import (
	"os"
	"testing"
	"time"
)

func TestNewWriter(t *testing.T) {
	pwd, err := os.Getwd()
	if err != nil {
		t.Error(err)
		return
	}
	t.Log("pwd:", pwd)

	writer, err := NewRawWriter("w_", ".log", pwd)
	if err != nil {
		t.Error(err)
		return
	}
	defer func() {
		_ = writer.Close()
	}()

	b := make([]byte, 4096)
	for i := 0; i < 4096; i++ {
		b[i] = byte(i)
	}
	n, err := writer.Write(b)
	if err != nil {
		t.Error(err)
		return
	}
	t.Log("w:", n)
}

func TestNewWriter2(t *testing.T) {
	pwd, err := os.Getwd()
	if err != nil {
		t.Error(err)
		return
	}
	t.Log("pwd:", pwd)

	writer, err := NewWriter("w_", ".log", pwd)
	defer func() {
		_ = writer.Close()
	}()

	time.Sleep(30 * time.Second)

	const (
		str1 = "[E] 1111111111111111111111111111111111111111111111\n"
		str2 = "[D] 2222222222222222222222222222222222222222222222\n"
	)

	go func() {
		for i := 0; i < 1000000; i++ {
			_, err = writer.Write([]byte(str1))
			if err != nil {
				t.Error(err)
				return
			}
		}
		t.Log("done1")
	}()

	go func() {
		for i := 0; i < 1000000; i++ {
			_, err = writer.Write([]byte(str2))
			if err != nil {
				t.Error(err)
				return
			}
		}
		t.Log("done2")
	}()

	time.Sleep(1 * time.Hour)
}

func BenchmarkNewWriter(b *testing.B) {
	pwd, err := os.Getwd()
	if err != nil {
		b.Error(err)
		return
	}
	b.Log("pwd:", pwd)

	writer, err := NewWriter("w_", ".log", pwd)
	defer func() {
		_ = writer.Close()
	}()

	const str = "1111111111111111111111111111111111111111111111\n"

	for i := 0; i < b.N; i++ {
		_, err = writer.Write([]byte(str))
		if err != nil {
			b.Error(err)
			return
		}
	}
}
