package core

import (
	"github.com/stretchr/testify/assert"
	"os"
	"testing"
)

func TestNewSqliteDB(t *testing.T) {
	dbFile := os.Getenv("TEST_DB")
	//	sql_driver.MakeTables(dbFile)
	db := NewSqliteDB(dbFile)
	defer db.CloseDb()

	testSignupLoginRenew(t, db)
	testSqliteDBRandomSvgInterface(t, db)
	//	if _, err := os.Stat(dbFile); err == nil {
	//		err = os.Remove(dbFile)
	//		assert.NoError(t, err)
	//	} else {
	//		assert.NoError(t, err)
	//	}
}

func testSignupLoginRenew(t *testing.T, db DbAccessor) {
	nkodePolicy := NewDefaultNKodePolicy()
	customerOrig, err := NewCustomer(nkodePolicy)
	assert.NoError(t, err)
	err = db.WriteNewCustomer(*customerOrig)
	assert.NoError(t, err)
	customer, err := db.GetCustomer(customerOrig.Id)
	assert.NoError(t, err)
	assert.Equal(t, customerOrig, customer)
	username := "test_user@example.com"
	kp := KeypadDefault
	passcodeIdx := []int{0, 1, 2, 3}
	mockSvgInterface := make(SvgIdInterface, kp.TotalAttrs())
	ui, err := NewUserInterface(&kp, mockSvgInterface)
	assert.NoError(t, err)
	userOrig, err := NewUser(*customer, username, passcodeIdx, *ui, kp)
	assert.NoError(t, err)
	err = db.WriteNewUser(*userOrig)
	assert.NoError(t, err)
	user, err := db.GetUser(UserEmail(username), customer.Id)
	assert.NoError(t, err)
	assert.Equal(t, userOrig, user)

	err = db.Renew(customer.Id)
	assert.NoError(t, err)

}

func testSqliteDBRandomSvgInterface(t *testing.T, db DbAccessor) {
	kp := KeypadMax
	svgs, err := db.RandomSvgInterface(kp)
	assert.NoError(t, err)
	assert.Len(t, svgs, kp.TotalAttrs())
}
