package login

import (
	"ddpf/model/dbm"
	"ddpf/test"
	"github.com/tangs-drm/go-tool/log"
	"github.com/tangs-drm/go-tool/util"
	"net/http"
	"testing"
	"time"
)

func init() {
	test.SqlConf = "../../ddpf.sql"
	test.Init()
	mux := http.NewServeMux()
	Router()
	SrvAddr = func() string {
		return "http://127.0.0.1:7890"
	}
	mux.HandleFunc("/login", Login)
	go func() {
		log.Debug("init start listen on 7890")
		err := http.ListenAndServe(":7890", mux)
		if err != nil {
			panic(err)
		}
	}()
	time.Sleep(3 * time.Second)
}

func TestDoLogin(t *testing.T) {
	var times int = 3
	for i := 0; i < times; i++ {
		testDogin(t, i)
	}
}

func testDogin(t *testing.T, times int) {
	var err error

	log.Debug("testDologin times %v --- START", times)
	// 准备用户数据
	// user 1
	var sqlCommand = "INSERT INTO USER(ID, NAME, ACCOUNT, PASSWORD, ROLE, STATUS, COLLEGE) value(?, ?, ?, ?, ?, ?, ?);"
	_, err = dbm.Db().Exec(sqlCommand, util.UUID(), "user1", "123", "123456", 1, "normal", "computer")
	if err != nil {
		t.Error(err)
		return
	}
	// user 2
	_, err = dbm.Db().Exec(sqlCommand, util.UUID(), "user2", "124", "123456", 1, "normal", "computer")
	if err != nil {
		t.Error(err)
		return
	}
	// user 3
	_, err = dbm.Db().Exec(sqlCommand, util.UUID(), "user4", "125", "123456", 1, "normal", "computer")
	if err != nil {
		t.Error(err)
		return
	}

	log.Debug("START to login")
	// login
	var username, password string
	var result util.Map

	// username/password is empty
	result, err = DoLogin(username, password)
	if err == nil {
		t.Error(err)
		return
	}
	log.Debug("result --- %v", util.S2Json(result))

	// user is not exist
	result, err = DoLogin("halo", "halo")
	if err == nil {
		t.Error(err)
		return
	}

	// password is invalid
	result, err = DoLogin("123", "halo")
	if err == nil {
		t.Error(err)
		return
	}

	// success
	result, err = DoLogin("123", "123456")
	if err != nil {
		t.Error(err)
		return
	}

	log.Debug("DoLogin success result --- %v", util.S2Json(result))
	log.Debug("testDogin times %v --- END", times)
}
