package pkg

import (
	"context"
	"github.com/julienschmidt/httprouter"
	"html/template"
	"net/http"
)

type LanguageOption struct {
	Tag  string
	Name string
}

type profileForm struct {
	locale          *Locale
	Name            *InputField
	Email           *InputField
	Password        *InputField
	PasswordConfirm *InputField
	Language        *SelectField
}

func newProfileForm(ctx context.Context, conn *Conn, locale *Locale) *profileForm {
	automaticOption := pgettext("language option", "Automatic", locale)
	languages := MustGetOptions(ctx, conn, "select 'und', $1 union all select lang_tag, endonym from language where selectable", automaticOption)
	return &profileForm{
		locale: locale,
		Name: &InputField{
			Name:     "name",
			Label:    pgettext("input", "User name", locale),
			Type:     "text",
			Required: true,
			Attributes: []template.HTMLAttr{
				`autocomplete="name"`,
			},
		},
		Email: &InputField{
			Name:     "email",
			Label:    pgettext("input", "Email", locale),
			Type:     "email",
			Required: true,
			Attributes: []template.HTMLAttr{
				`autocomplete="username"`,
			},
		},
		Password: &InputField{
			Name:  "password",
			Label: pgettext("input", "Password", locale),
			Type:  "password",
			Attributes: []template.HTMLAttr{
				`autocomplete="new-password"`,
			},
		},
		PasswordConfirm: &InputField{
			Name:  "password_confirm",
			Label: pgettext("input", "Password Confirmation", locale),
			Type:  "password",
			Attributes: []template.HTMLAttr{
				`autocomplete="new-password"`,
			},
		},
		Language: &SelectField{
			Name:     "language",
			Label:    pgettext("input", "Language", locale),
			Options:  languages,
			Required: true,
			Attributes: []template.HTMLAttr{
				`autocomplete="language"`,
			},
		},
	}
}

func (form *profileForm) Parse(r *http.Request) error {
	if err := r.ParseForm(); err != nil {
		return err
	}
	form.Email.FillValue(r)
	form.Name.FillValue(r)
	form.Password.FillValue(r)
	form.PasswordConfirm.FillValue(r)
	form.Language.FillValue(r)
	return nil
}

func (form *profileForm) Validate() bool {
	validator := newFormValidator()
	if validator.CheckRequiredInput(form.Email, gettext("Email can not be empty.", form.locale)) {
		validator.CheckValidEmailInput(form.Email, gettext("This value is not a valid email. It should be like name@domain.com.", form.locale))
	}
	validator.CheckRequiredInput(form.Name, gettext("Name can not be empty.", form.locale))
	validator.CheckPasswordConfirmation(form.Password, form.PasswordConfirm, gettext("Confirmation does not match password.", form.locale))
	validator.CheckValidSelectOption(form.Language, gettext("Selected language is not valid.", form.locale))
	return validator.AllOK()
}

func GetProfileForm(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	user := getUser(r)
	conn := getConn(r)
	locale := getLocale(r)
	form := newProfileForm(r.Context(), conn, locale)
	form.Name.Val = conn.MustGetText(r.Context(), "", "select name from user_profile")
	form.Email.Val = user.Email
	form.Language.Selected = []string{user.Language.String()}

	w.WriteHeader(http.StatusOK)
	mustRenderProfileForm(w, r, form)
}

func HandleProfileForm(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	conn := getConn(r)
	locale := getLocale(r)
	form := newProfileForm(r.Context(), conn, locale)
	if err := form.Parse(r); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	if err := verifyCsrfTokenValid(r); err != nil {
		http.Error(w, err.Error(), http.StatusForbidden)
		return
	}
	if ok := form.Validate(); !ok {
		w.WriteHeader(http.StatusUnprocessableEntity)
		mustRenderProfileForm(w, r, form)
		return
	}
	//goland:noinspection SqlWithoutWhere
	cookie := conn.MustGetText(r.Context(), "", "update user_profile set name = $1, email = $2, lang_tag = $3 returning build_cookie()", form.Name, form.Email, form.Language)
	setSessionCookie(w, cookie)
	if form.Password.Val != "" {
		conn.MustExec(r.Context(), "select change_password($1)", form.Password)
	}
	company := mustGetCompany(r)
	http.Redirect(w, r, companyURI(company, "/profile"), http.StatusSeeOther)
}

func mustRenderProfileForm(w http.ResponseWriter, r *http.Request, form *profileForm) {
	mustRenderAppTemplate(w, r, "profile.gohtml", form)
}
