package handlers

import (
	"encoding/json"
	"errors"
	"github.com/Pena-Co-Ltd/amocrm_templategen_back/amo"
	"github.com/Pena-Co-Ltd/amocrm_templategen_back/dal"
	"github.com/Pena-Co-Ltd/amocrm_templategen_back/dal/model"
	GDisk "github.com/Pena-Co-Ltd/amocrm_templategen_back/gdisk"
	"github.com/Pena-Co-Ltd/amocrm_templategen_back/middleware"
	YaDisk "github.com/Pena-Co-Ltd/amocrm_templategen_back/yadisk"
	"go.uber.org/zap"
	"html/template"
	"io/ioutil"
	"net/http"
)

type Handlers struct {
	dal    *dal.MongoDAL
	YaDisk *YaDisk.ClientApp
	GDisk  *GDisk.ClientApp
	Amo    *amo.ClientApp
	logger *zap.Logger
}

func NewHandlers(dal *dal.MongoDAL, yaDisk *YaDisk.ClientApp, gDisk *GDisk.ClientApp, amo *amo.ClientApp,
	logger *zap.Logger) *Handlers {
	return &Handlers{dal, yaDisk, gDisk, amo, logger}
}

// LOCAL FUNCTIONS

func execTemplate(tplFile string, data interface{}, w http.ResponseWriter) error {
	tpl := template.Must(template.ParseFiles("./template/"+tplFile, "./template/header.gohtml",
		"./template/footer.gohtml"))
	return tpl.Execute(w, data)
}

func sendResponse(w http.ResponseWriter, status int, response interface{}) error {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(status)
	return json.NewEncoder(w).Encode(response)
}

func (h *Handlers) reportError(w http.ResponseWriter, err error, status int) {
	h.logger.Error("ErrorHandler", zap.Error(err))
	sendResponse(w, status, err.Error())
}

func getAmoByJwt(r *http.Request) *model.Amo {
	amoData, ok := r.Context().Value("amoData").(*model.Amo)
	if ok {
		return amoData
	}

	return nil
}

func getJwtUser(r *http.Request) *middleware.UserClaims {
	user, ok := r.Context().Value("JWT").(*middleware.UserClaims)
	if ok {
		return user
	}

	return nil
}

func decodePost(s interface{}, r *http.Request) error {
	reqBody, err := ioutil.ReadAll(r.Body)

	if err != nil {
		return err
	}

	err = json.Unmarshal(reqBody, s)

	return err
}

// ERRORS

var ErrorUnauthorized = errors.New("unauthorized")
