package login

import (
	"ddpf/model/session"
	"ddpf/model/user"
	"ddpf/response"
	"fmt"
	"github.com/tangs-drm/go-tool/log"
	"github.com/tangs-drm/go-tool/util"
	"net/http"
	"strings"
)

func Login(w http.ResponseWriter, r *http.Request) {
	var code int
	var err error
	var msg string
	var data util.Map
	defer func() {
		msg = response.Message[code]
		response.WriteResponse(w, code, msg, err, data)
	}()
	username := r.FormValue("account")
	password := r.FormValue("password")

	if len(username) < 1 || len(password) < 1 {
		err = util.Error("username/password contain a empty value")
		log.Error("Login receive invalid username/password ->(%v)", err)
		code = 100
		return
	}

	// check user if exists
	var isExist bool
	isExist, err = user.ExistUser(username)
	if err != nil {
		log.Error("Login receive username(%v) ExistUser error ->(%v)", username, err)
		code = 2
		return
	}
	if !isExist {
		log.Debug("Login receive username(%v) is not exist", username)
		code = 101
		return
	}

	// check user password
	var usr *user.User
	usr, err = user.CheckPassword(username, password)
	if err != nil {
		log.Error("Login receive username(%v) check password error ->(%v)", username, err)
		code = 2
		return
	}
	if len(usr.Id) < 1 {
		log.Debug("Login receive username(%v) password is incorrect", username)
		code = 102
		return
	}

	// 创建session
	sess, err := session.CreateSession(usr.Id)
	if err != nil {
		log.Error("Login create session by uid(%v) error ->(%v)", usr.Id, err)
		code = 2
		return
	}

	cookie := &http.Cookie{Name: "token", Value: sess.Id, Domain: "/"}
	http.SetCookie(w, cookie)
	log.Debug("Login with account(%v) success", username)
	return
}

// DoLogin 为了测试的时候方便调用的方式，用户测试
func DoLogin(username string, password string) (util.Map, error) {
	url := fmt.Sprintf("%v/login?account=%v&password=%v", SrvAddr(), username, password)

	var headers = map[string]string{
		"Content-Type": "application/x-www-form-urlencoded",
	}
	var reqBody = util.Map{
		"account":  username,
		"password": password,
	}
	body := strings.NewReader(util.S2Json(reqBody))
	res, err := util.HTTPPostMap(url, headers, body)
	if err != nil {
		return nil, err
	}
	if res.Int("code") != 0 {
		return nil, util.Error("%v", res.Int("code"))
	}
	return res, nil
}
