package account

import (
	"os"
	"testing"
	"time"

	"code.revolvingcow.com/revolvingcow/loop/environment"
)

func TestGetAccounts(t *testing.T) {
	a, err := getAccounts()
	if err != nil || a == nil {
		t.Error(err)
	}
}

func TestCreate(t *testing.T) {
	a := Account{
		Username:   "guest",
		Passphrase: "guest",
	}

	environment.ConfigureEnvironment()
	err := a.Create()
	if err != nil {
		t.Error(err)
	}

	valid, err := a.Validate()
	if err != nil {
		t.Error(err)
	}
	if !valid {
		t.Error("Failed to create account")
	}
}

func TestValidate(t *testing.T) {
	a := Account{
		Username:   "fake",
		Passphrase: "fake",
	}

	valid, err := a.Validate()
	if err != nil {
		t.Error(err)
	}
	if valid {
		t.Error("Fake account should not exist")
	}
}

func TestAdd(t *testing.T) {
	a := Account{
		Username:   "guest",
		Passphrase: "guest",
	}

	environment.ConfigureEnvironment()
	fp, err := a.Add("", "", []byte{})
	if err == nil {
		t.Error("Fake content should not be publishable")
	}

	fp, err = a.Add("", "README.md", []byte{})
	if fp == "" {
		t.Error("File name should have been returned")
	}
	if err != nil {
		t.Error(err)
	}
}

func TestPublish(t *testing.T) {
	a := Account{
		Username:   "guest",
		Passphrase: "guest",
	}

	environment.ConfigureEnvironment()
	err := a.Publish("My first blog post", "thisshouldnotexist", time.Now())
	if err == nil {
		t.Error("Fake content should not be publishable")
	}
}

func TestDelete(t *testing.T) {
	a := Account{
		Username:   "guest",
		Passphrase: "guest",
	}

	environment.ConfigureEnvironment()
	err := a.Delete()
	if err != nil {
		t.Error(err)
	}

	valid, err := a.Validate()
	if err != nil {
		t.Error(err)
	}
	if valid {
		t.Error("Failed to delete account")
	}
}

func TestCleanup(t *testing.T) {
	err := os.Remove("loop_users")
	if err != nil {
		t.Error(err)
	}
}
