package handler

import (
	"bytes"
	"errors"
	"github.com/gorilla/csrf"
	"html/template"
	"log"
	"net/http"
	"status/model"
	"status/web/handler/form"
)

func (h *Handler) handleRegister(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		h.showRegisterView(w, r)
	case "POST":
		h.register(w, r)
	}
}

func (h *Handler) showRegisterView(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		h.renderLayout(w, "register", map[string]interface{}{
			csrf.TemplateTag: csrf.TemplateField(r),
		}, "")
	}
}

type keyStatus struct {
	Success bool `json:"success"`
	Uses    int  `json:"uses"`
}

//func verifyKey(key string) error {
//	hc := http.Client{}
//
//	f := url.Values{}
//	f.Add("product_permalink", "YccHL")
//	f.Add("license_key", key)
//	req, err := http.NewRequest("POST", "https://api.gumroad.com/v2/licenses/verify", strings.NewReader(f.Encode()))
//	if err != nil {
//		return err
//	}
//	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
//
//	resp, err := hc.Do(req)
//	if err != nil {
//		return err
//	}
//
//	if resp.Body != nil {
//		defer resp.Body.Close()
//	}
//
//	body, readErr := ioutil.ReadAll(resp.Body)
//	if readErr != nil {
//		return err
//	}
//
//	ks := keyStatus{}
//	jsonErr := json.Unmarshal(body, &ks)
//	if jsonErr != nil {
//		return err
//	}
//
//	if ks.Success != true || ks.Uses > 1 {
//		return errors.New("invalid license key")
//	}
//
//	return nil
//}

func buildIndex(t *template.Template, name string) []byte {
	html := bytes.NewBufferString("")
	err := t.Execute(html, name)
	if err != nil {
		log.Fatal(err)
	}
	return html.Bytes()
}

func (h *Handler) register(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "POST":
		f := form.NewRegisterForm(r)
		showError := func(err error) {
			f.Error = err.Error()
			h.renderLayout(w, "register", map[string]interface{}{"form": *f, csrf.TemplateTag: csrf.TemplateField(r)}, "")
			return
		}
		if err := f.Validate(); err != nil {
			showError(err)
			return
		}
		user := model.User{
			Name:        f.Username,
			Password:    f.Password,
			SignupEmail: f.Email,
			SignupMsg:   f.Answer,
		}
		if f.ShowEmail {
			user.Email = f.Email
		}
		if err := user.Validate(); err != nil {
			showError(err)
			return
		}
		if h.storage.UserExists(user.Name) {
			showError(errors.New("username already exists"))
			return
		}
		if !h.cfg.ManualRegistration {
			user.Active = true
		}
		if err := h.storage.CreateUser(user); err != nil {
			showError(err)
			return
		}
		if h.cfg.ManualRegistration {
			h.renderLayout(w, "register-success", map[string]interface{}{
				"name":  user.Name,
				"email": user.SignupEmail,
			}, "")
		} else {
			if err := h.sess.Save(r, w, r.FormValue("name")); err != nil {
				serverError(w, err)
				return
			}
			http.Redirect(w, r, "/", http.StatusFound)
		}
	}
}
