package bench_test

import (
	"io"
	"io/ioutil"
	"os"
	"path"
	"testing"

	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/bazil.org/fuse"
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/bazil.org/fuse/fs"
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/bazil.org/fuse/fs/fstestutil"
)

type benchConfig struct {
	directIO bool
}

type benchFS struct {
	conf *benchConfig
}

var _ = fs.FS(benchFS{})
var _ = fs.FSIniter(benchFS{})

func (benchFS) Init(req *fuse.InitRequest, resp *fuse.InitResponse, intr fs.Intr) fuse.Error {
	resp.MaxReadahead = 64 * 1024 * 1024
	resp.Flags |= fuse.InitAsyncRead
	return nil
}

func (f benchFS) Root() (fs.Node, fuse.Error) {
	return benchDir{conf: f.conf}, nil
}

type benchDir struct {
	conf *benchConfig
}

var _ = fs.Node(benchDir{})
var _ = fs.NodeStringLookuper(benchDir{})
var _ = fs.Handle(benchDir{})
var _ = fs.HandleReadDirer(benchDir{})

func (benchDir) Attr() fuse.Attr {
	return fuse.Attr{Inode: 1, Mode: os.ModeDir | 0555}
}

func (d benchDir) Lookup(name string, intr fs.Intr) (fs.Node, fuse.Error) {
	if name == "bench" {
		return benchFile{conf: d.conf}, nil
	}
	return nil, fuse.ENOENT
}

func (benchDir) ReadDir(intr fs.Intr) ([]fuse.Dirent, fuse.Error) {
	l := []fuse.Dirent{
		{Inode: 2, Name: "bench", Type: fuse.DT_File},
	}
	return l, nil
}

type benchFile struct {
	conf *benchConfig
}

var _ = fs.Node(benchFile{})
var _ = fs.NodeOpener(benchFile{})
var _ = fs.NodeFsyncer(benchFile{})
var _ = fs.Handle(benchFile{})
var _ = fs.HandleReader(benchFile{})
var _ = fs.HandleWriter(benchFile{})

func (benchFile) Attr() fuse.Attr {
	return fuse.Attr{Inode: 2, Mode: 0644, Size: 9999999999999999}
}

func (f benchFile) Open(req *fuse.OpenRequest, resp *fuse.OpenResponse, intr fs.Intr) (fs.Handle, fuse.Error) {
	if f.conf.directIO {
		resp.Flags |= fuse.OpenDirectIO
	}
	// TODO configurable?
	resp.Flags |= fuse.OpenKeepCache
	return f, nil
}

func (benchFile) Read(req *fuse.ReadRequest, resp *fuse.ReadResponse, intr fs.Intr) fuse.Error {
	resp.Data = resp.Data[:cap(resp.Data)]
	return nil
}

func (benchFile) Write(req *fuse.WriteRequest, resp *fuse.WriteResponse, intr fs.Intr) fuse.Error {
	resp.Size = len(req.Data)
	return nil
}

func (benchFile) Fsync(req *fuse.FsyncRequest, intr fs.Intr) fuse.Error {
	return nil
}

func benchmark(b *testing.B, fn func(b *testing.B, mnt string), conf *benchConfig) {
	srv := &fs.Server{
		FS: benchFS{
			conf: conf,
		},
	}
	mnt, err := fstestutil.Mounted(srv)
	if err != nil {
		b.Fatal(err)
	}
	defer mnt.Close()

	fn(b, mnt.Dir)
}

type zero struct{}

func (zero) Read(p []byte) (n int, err error) {
	return len(p), nil
}

var Zero io.Reader = zero{}

func doWrites(size int64) func(b *testing.B, mnt string) {
	return func(b *testing.B, mnt string) {
		p := path.Join(mnt, "bench")

		f, err := os.Create(p)
		if err != nil {
			b.Fatalf("create: %v", err)
		}
		defer f.Close()

		b.ResetTimer()
		b.SetBytes(size)

		for i := 0; i < b.N; i++ {
			_, err = io.CopyN(f, Zero, size)
			if err != nil {
				b.Fatalf("write: %v", err)
			}
		}
	}
}

func BenchmarkWrite100(b *testing.B) {
	benchmark(b, doWrites(100), &benchConfig{})
}

func BenchmarkWrite10MB(b *testing.B) {
	benchmark(b, doWrites(10*1024*1024), &benchConfig{})
}

func BenchmarkWrite100MB(b *testing.B) {
	benchmark(b, doWrites(100*1024*1024), &benchConfig{})
}

func BenchmarkDirectWrite100(b *testing.B) {
	benchmark(b, doWrites(100), &benchConfig{
		directIO: true,
	})
}

func BenchmarkDirectWrite10MB(b *testing.B) {
	benchmark(b, doWrites(10*1024*1024), &benchConfig{
		directIO: true,
	})
}

func BenchmarkDirectWrite100MB(b *testing.B) {
	benchmark(b, doWrites(100*1024*1024), &benchConfig{
		directIO: true,
	})
}

func doWritesSync(size int64) func(b *testing.B, mnt string) {
	return func(b *testing.B, mnt string) {
		p := path.Join(mnt, "bench")

		f, err := os.Create(p)
		if err != nil {
			b.Fatalf("create: %v", err)
		}
		defer f.Close()

		b.ResetTimer()
		b.SetBytes(size)

		for i := 0; i < b.N; i++ {
			_, err = io.CopyN(f, Zero, size)
			if err != nil {
				b.Fatalf("write: %v", err)
			}

			if err := f.Sync(); err != nil {
				b.Fatalf("sync: %v", err)
			}
		}
	}
}

func BenchmarkWriteSync100(b *testing.B) {
	benchmark(b, doWritesSync(100), &benchConfig{})
}

func BenchmarkWriteSync10MB(b *testing.B) {
	benchmark(b, doWritesSync(10*1024*1024), &benchConfig{})
}

func BenchmarkWriteSync100MB(b *testing.B) {
	benchmark(b, doWritesSync(100*1024*1024), &benchConfig{})
}

func doReads(size int64) func(b *testing.B, mnt string) {
	return func(b *testing.B, mnt string) {
		p := path.Join(mnt, "bench")

		f, err := os.Open(p)
		if err != nil {
			b.Fatalf("close: %v", err)
		}
		defer f.Close()

		b.ResetTimer()
		b.SetBytes(size)

		for i := 0; i < b.N; i++ {
			n, err := io.CopyN(ioutil.Discard, f, size)
			if err != nil {
				b.Fatalf("read: %v", err)
			}
			if n != size {
				b.Errorf("unexpected size: %d != %d", n, size)
			}
		}
	}
}

func BenchmarkRead100(b *testing.B) {
	benchmark(b, doReads(100), &benchConfig{})
}

func BenchmarkRead10MB(b *testing.B) {
	benchmark(b, doReads(10*1024*1024), &benchConfig{})
}

func BenchmarkRead100MB(b *testing.B) {
	benchmark(b, doReads(100*1024*1024), &benchConfig{})
}

func BenchmarkDirectRead100(b *testing.B) {
	benchmark(b, doReads(100), &benchConfig{
		directIO: true,
	})
}

func BenchmarkDirectRead10MB(b *testing.B) {
	benchmark(b, doReads(10*1024*1024), &benchConfig{
		directIO: true,
	})
}

func BenchmarkDirectRead100MB(b *testing.B) {
	benchmark(b, doReads(100*1024*1024), &benchConfig{
		directIO: true,
	})
}
