package nkode

import (
	"github.com/stretchr/testify/assert"
	m "go-nkode/core/model"
	"os"
	"testing"
)

func TestNKodeAPI(t *testing.T) {
	//db1 := NewInMemoryDb()
	//1testNKodeAPI(t, &db1)

	dbFile := "test.db"
	db2, err := NewSqliteDB(dbFile)
	assert.NoError(t, err)
	testNKodeAPI(t, db2)
	if _, err := os.Stat(dbFile); err == nil {
		err = os.Remove(dbFile)
		assert.NoError(t, err)
	} else {
		assert.NoError(t, err)
	}
}

func testNKodeAPI(t *testing.T, db DbAccessor) {

	for idx := 0; idx < 10; idx++ {
		username := m.Username("test_username")
		passcodeLen := 4
		nkodePolicy := m.NewDefaultNKodePolicy()
		keypadSize := m.KeypadDimension{AttrsPerKey: 10, NumbOfKeys: 8}
		nkodeApi := NewNKodeAPI(db)
		customerId, err := nkodeApi.CreateNewCustomer(nkodePolicy, nil)
		assert.NoError(t, err)
		signupResponse, err := nkodeApi.GenerateSignupInterface(username, *customerId, keypadSize)
		assert.NoError(t, err)
		setInterface := signupResponse.UserInterface
		sessionId := signupResponse.SessionId
		keypadSize = m.KeypadDimension{AttrsPerKey: 8, NumbOfKeys: 8}
		userPasscode := setInterface[:passcodeLen]
		setKeySelect, err := m.SelectKeyByAttrIdx(setInterface, userPasscode, keypadSize)
		assert.NoError(t, err)
		confirmInterface, err := nkodeApi.SetNKode(*customerId, sessionId, setKeySelect)
		assert.NoError(t, err)
		confirmKeySelect, err := m.SelectKeyByAttrIdx(confirmInterface, userPasscode, keypadSize)
		err = nkodeApi.ConfirmNKode(*customerId, sessionId, confirmKeySelect)
		assert.NoError(t, err)

		keypadSize = m.KeypadDimension{AttrsPerKey: 10, NumbOfKeys: 8}
		loginInterface, err := nkodeApi.GetLoginInterface(username, *customerId)
		assert.NoError(t, err)
		loginKeySelection, err := m.SelectKeyByAttrIdx(loginInterface, userPasscode, keypadSize)
		assert.NoError(t, err)
		err = nkodeApi.Login(*customerId, username, loginKeySelection)
		assert.NoError(t, err)

		err = nkodeApi.RenewAttributes(*customerId)
		assert.NoError(t, err)

		loginInterface, err = nkodeApi.GetLoginInterface(username, *customerId)
		assert.NoError(t, err)
		loginKeySelection, err = m.SelectKeyByAttrIdx(loginInterface, userPasscode, keypadSize)
		assert.NoError(t, err)
		err = nkodeApi.Login(*customerId, username, loginKeySelection)
		assert.NoError(t, err)

	}
}
