package main

import (
	"encoding/json"
	"fmt"
	"html/template"
	"io"
	"net/http"
	"path/filepath"

	"redisdog/model"
)

type LoginRet struct {
	Errno int     `json:"errno"`
	Error string  `json:"error"`
	Data  Session `json:"data"`
}

func login_index(resp http.ResponseWriter, req *http.Request) {
	if req.Method == "GET" {
		//视图输出
		tmpl, err := template.ParseFiles(filepath.Join(Cfg.TmplDir, "login.tmpl"))
		if err != nil {
			io.WriteString(resp, fmt.Sprintf("Error: %s\n", err.Error()))
		} else {
			tmpl.Execute(resp, req)
		}
	} else if req.Method == "POST" {
		req.ParseForm()
		account := req.PostForm.Get("account")
		passwd := req.PostForm.Get("passwd")
		if account == "" {
			resp.Write(ERROR_RET(1, "用户名不能为空!"))
		} else if passwd == "" {
			resp.Write(ERROR_RET(2, "密码不能为空!"))
		} else {
			mdlAccounts := model.NewAccounts(Db)
			row, err := mdlAccounts.Login(account, passwd)
			if err != nil {
				resp.Write(ERROR_RET(3, err.Error()))
			} else {
				sessid := makeSessionId(req.RemoteAddr)
				sess := Session{
					Sess:    sessid,
					Account: row,
				}
				SessPoll.Set(sessid, &sess)
				cookie := &http.Cookie{
					Name:  "sessid",
					Value: sessid,
					Path:  "/",
				}
				resp.Header().Add("Set-Cookie", cookie.String())
				ret, _ := json.Marshal(LoginRet{Errno: 0, Error: "", Data: sess})
				resp.Write(ret)
			}
		}
	}
}
