package model

import (
	"encoding/json"
	"errors"
	"go-nkode/core/api"
	"log"
	"net/http"
)

type NKodeHandler struct {
	Api NKodeAPIInterface
}

func (h *NKodeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	switch r.URL.Path {
	case api.CreateNewCustomer:
		h.CreateNewCustomerHandler(w, r)
	case api.GenerateSignupInterface:
		h.GenerateSignupInterfaceHandler(w, r)
	case api.SetNKode:
		h.SetNKodeHandler(w, r)
	case api.ConfirmNKode:
		h.ConfirmNKodeHandler(w, r)
	case api.GetLoginInterface:
		h.GetLoginInterfaceHandler(w, r)
	case api.Login:
		h.LoginHandler(w, r)
	case api.RenewAttributes:
		h.RenewAttributesHandler(w, r)
	default:
		w.WriteHeader(http.StatusNotFound)
		_, err := w.Write([]byte("404 not found"))
		log.Println(err)
	}
}

func (h *NKodeHandler) CreateNewCustomerHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		methodNotAllowed(w)
		return
	}
	var customerPost NewCustomerPost
	err := decodeJson(w, r, &customerPost)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}
	customerId, err := h.Api.CreateNewCustomer(customerPost.NKodePolicy, nil)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}
	respBody := CreateNewCustomerResp{
		CustomerId: *customerId,
	}
	respBytes, err := json.Marshal(respBody)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}
	_, err = w.Write(respBytes)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}

	w.WriteHeader(http.StatusOK)
}

func (h *NKodeHandler) GenerateSignupInterfaceHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		methodNotAllowed(w)
		return
	}

	var signupPost GenerateSignupInterfacePost
	err := decodeJson(w, r, &signupPost)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}
	kp := KeypadDimension{
		AttrsPerKey: signupPost.AttrsPerKey,
		NumbOfKeys:  signupPost.NumbOfKeys,
	}
	err = kp.IsValidKeypadDimension()
	if err != nil {
		keypadSizeOutOfRange(w)
		log.Println(err)
		return
	}
	resp, err := h.Api.GenerateSignupInterface(signupPost.Username, signupPost.CustomerId, kp)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}
	respBytes, err := json.Marshal(resp)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}

	_, err = w.Write(respBytes)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}

	w.WriteHeader(http.StatusOK)
}

func (h *NKodeHandler) SetNKodeHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		methodNotAllowed(w)
		return
	}
	var setNKodePost SetNKodePost
	err := decodeJson(w, r, &setNKodePost)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}
	confirmInterface, err := h.Api.SetNKode(setNKodePost.CustomerId, setNKodePost.SessionId, setNKodePost.KeySelection)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}
	respBody := SetNKodeResp{UserInterface: confirmInterface}

	respBytes, err := json.Marshal(respBody)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}

	_, err = w.Write(respBytes)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}

	w.WriteHeader(http.StatusOK)
}

func (h *NKodeHandler) ConfirmNKodeHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		methodNotAllowed(w)
		return
	}

	var confirmNKodePost ConfirmNKodePost
	err := decodeJson(w, r, &confirmNKodePost)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}
	err = h.Api.ConfirmNKode(confirmNKodePost.CustomerId, confirmNKodePost.SessionId, confirmNKodePost.KeySelection)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}

	w.WriteHeader(http.StatusOK)

}

func (h *NKodeHandler) GetLoginInterfaceHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		methodNotAllowed(w)
		return
	}
	var loginInterfacePost GetLoginInterfacePost
	err := decodeJson(w, r, &loginInterfacePost)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}
	loginInterface, err := h.Api.GetLoginInterface(loginInterfacePost.Username, loginInterfacePost.CustomerId)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}

	respBody := GetLoginInterfaceResp{UserInterface: loginInterface}
	respBytes, err := json.Marshal(respBody)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}
	_, err = w.Write(respBytes)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}

	w.WriteHeader(http.StatusOK)

}

func (h *NKodeHandler) LoginHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		methodNotAllowed(w)
		return
	}
	var loginPost LoginPost
	err := decodeJson(w, r, &loginPost)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}
	err = h.Api.Login(loginPost.CustomerId, loginPost.Username, loginPost.KeySelection)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}

	w.WriteHeader(http.StatusOK)
}

func (h *NKodeHandler) RenewAttributesHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		methodNotAllowed(w)
		return
	}
	var renewAttributesPost RenewAttributesPost
	err := decodeJson(w, r, &renewAttributesPost)

	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}

	err = h.Api.RenewAttributes(renewAttributesPost.CustomerId)
	if err != nil {
		internalServerErrorHandler(w)
		log.Println(err)
		return
	}

	w.WriteHeader(http.StatusOK)
}

func decodeJson(w http.ResponseWriter, r *http.Request, post any) error {
	if r.Body == nil {
		invalidJson(w)
		return errors.New("invalid json")
	}
	err := json.NewDecoder(r.Body).Decode(&post)
	if err != nil {
		internalServerErrorHandler(w)
		return err
	}
	return nil
}

func internalServerErrorHandler(w http.ResponseWriter) {
	w.WriteHeader(http.StatusInternalServerError)
	w.Write([]byte("500 Internal Server Error"))
}

func methodNotAllowed(w http.ResponseWriter) {
	w.WriteHeader(http.StatusMethodNotAllowed)
	w.Write([]byte("405 method not allowed"))
}

func keypadSizeOutOfRange(w http.ResponseWriter) {
	w.WriteHeader(http.StatusBadRequest)
	w.Write([]byte("invalid keypad dimensions"))
}

func invalidJson(w http.ResponseWriter) {
	w.WriteHeader(http.StatusBadRequest)
	w.Write([]byte("invalid json"))
}
