package handlers

import (
	"errors"
	"github.com/Pena-Co-Ltd/amocrm_templategen_back/dal/model"
	"net/http"
)

type RespTemplateNew struct {
	Name     string `json:"name"`
	Filename string `json:"filename"`
	Storage  string `json:"storage"`
}

func (h *Handlers) TemplateNew(w http.ResponseWriter, r *http.Request) {
	var resp RespTemplateNew

	user := getJwtUser(r)

	if user == nil {
		h.reportError(w, ErrorUnauthorized, http.StatusUnauthorized)
		return
	}

	err := decodePost(&resp, r)

	if err != nil {
		h.reportError(w, err, http.StatusBadRequest)
		return
	}

	if resp.Name == "" || resp.Filename == "" {
		err = errors.New("got empty name or filename")
		h.reportError(w, err, http.StatusBadRequest)
		return
	}

	_, err = h.dal.Template.Insert(r.Context(), &model.Template{
		UserID:    user.UserID,
		Name:      resp.Name,
		Filename:  resp.Filename,
		StorageID: resp.Storage,
		IsDeleted: false,
	})

	if err != nil {
		h.reportError(w, err, http.StatusInternalServerError)
		return
	}
}

func (h *Handlers) TemplateGetListByUser(w http.ResponseWriter, r *http.Request) {
	user := getJwtUser(r)

	if user == nil {
		h.reportError(w, ErrorUnauthorized, http.StatusUnauthorized)
		return
	}

	result, err := h.dal.Template.GetListByUserID(r.Context(), user.UserID)
	if err != nil {
		h.reportError(w, err, http.StatusInternalServerError)
		return
	}

	sendResponse(w, 200, result)
}

type RespTemplateGetByID struct {
	ID string `json:"id"`
}

func (h *Handlers) TemplateGetByID(w http.ResponseWriter, r *http.Request) {
	var resp RespTemplateGetByID

	user := getJwtUser(r)

	if user == nil {
		h.reportError(w, ErrorUnauthorized, http.StatusUnauthorized)
		return
	}

	err := decodePost(&resp, r)

	if err != nil {
		h.reportError(w, err, http.StatusBadRequest)
		return
	}

	if resp.ID == "" {
		h.reportError(w, err, http.StatusBadRequest)
		return
	}

	result, err := h.dal.Template.GetByID(r.Context(), resp.ID)

	if err != nil {
		h.reportError(w, err, http.StatusInternalServerError)
		return
	}

	sendResponse(w, 200, result)
}

type RespTemplateUpdate struct {
	ID               string `json:"id"`
	Name             string `json:"name"`
	TemplateFilename string `json:"template_filename"`
}

func (h *Handlers) TemplateUpdate(w http.ResponseWriter, r *http.Request) {
	var resp RespTemplateUpdate

	user := getJwtUser(r)

	if user == nil {
		h.reportError(w, ErrorUnauthorized, http.StatusUnauthorized)
		return
	}

	err := decodePost(&resp, r)

	if err != nil {
		h.reportError(w, err, http.StatusBadRequest)
		return
	}

	if resp.Name == "" && resp.TemplateFilename == "" {
		h.reportError(w, err, http.StatusBadRequest)
		return
	}

	record := &model.Template{
		ID:       resp.ID,
		UserID:   user.UserID,
		Name:     resp.Name,
		Filename: resp.TemplateFilename,
	}

	if resp.ID != "" {
		err = h.dal.Template.UpdateByID(r.Context(), record)
	} else {
		err = h.dal.Template.UpdateByNameAndUserID(r.Context(), record)
	}

	if err != nil {
		h.reportError(w, err, http.StatusInternalServerError)
		return
	}

	sendResponse(w, 200, nil)
}

type RespTemplateDelete struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

func (h *Handlers) TemplateDelete(w http.ResponseWriter, r *http.Request) {
	var resp RespTemplateDelete

	user := getJwtUser(r)

	if user == nil {
		h.reportError(w, ErrorUnauthorized, http.StatusUnauthorized)
		return
	}

	err := decodePost(&resp, r)

	if err != nil {
		h.reportError(w, err, http.StatusBadRequest)
		return
	}

	if resp.ID == "" && resp.Name == "" {
		h.reportError(w, err, http.StatusBadRequest)
		return
	}

	if resp.ID != "" {
		err = h.dal.Template.DeleteByID(r.Context(), resp.ID)
	} else {
		err = h.dal.Template.DeleteByNameAndUserID(r.Context(), resp.Name, user.UserID)
	}

	if err != nil {
		h.reportError(w, err, http.StatusInternalServerError)
		return
	}

	sendResponse(w, 200, nil)
}

type RespTemplateInit struct {
	EventName string                 `json:"event_name"`
	Data      map[string]interface{} `json:"data"`
}

func (h *Handlers) TemplateInit(w http.ResponseWriter, r *http.Request) {
	//var resp RespTemplateInit
	//
	//user := getJwtUser(r)
	//
	//if user == nil {
	//	h.reportError(w, ErrorUnauthorized, http.StatusUnauthorized)
	//	return
	//}
	//
	//err := decodePost(&resp, r)
	//
	//if err != nil {
	//	h.reportError(w, err, http.StatusBadRequest)
	//	return
	//}
	//
	//// Ищем ивент
	//t, err := h.dal.Template.GetByNameAndUserID(r.Context(), resp.EventName, user.UserID)
	//
	//if err != nil {
	//	h.reportError(w, err, http.StatusInternalServerError)
	//	return
	//}
	//
	//if t == nil {
	//	h.reportError(w, errors.New("template not found"), http.StatusNotFound)
	//	return
	//}
	//
	//YaDiskData, err := h.dal.YaDisk.GetByUserID(r.Context(), user.UserID)
	//if err != nil {
	//	h.reportError(w, err, http.StatusInternalServerError)
	//	return
	//}
	//
	//if YaDiskData == nil {
	//	h.reportError(w, errors.New("YaDisk not found"), http.StatusNotFound)
	//	return
	//}
	//
	//// download file
	//token := &oauth2.Token{
	//	AccessToken:  YaDiskData.AccessToken,
	//	TokenType:    YaDiskData.TokenType,
	//	RefreshToken: YaDiskData.RefreshToken,
	//	Expiry:       YaDiskData.ExpiresIn,
	//}
	//
	//if !token.Valid() {
	//	h.reportError(w, errors.New("invalid yandex token"), http.StatusForbidden)
	//	return
	//}
	//
	//client := h.YaDisk.NewClient(token)
	//
	//res, err := client.GetResources(YaDiskData.TemplateFolder + "/" + t.Filename)
	//
	//if res == nil {
	//	h.reportError(w, errors.New("resource in yandex disk not found"), http.StatusNotFound)
	//	return
	//}
	//downloadFileName := fmt.Sprintf("./tmp/downloaded/%v_%v", t.UserID, t.Filename)
	//
	//err = templategen.DownloadDocument(downloadFileName, res.File)
	//if err != nil {
	//	h.reportError(w, err, http.StatusInternalServerError)
	//	return
	//}
	//
	//// parsing file
	//dc, err := docTemp.GetTemplate(downloadFileName)
	//if err != nil {
	//	h.reportError(w, err, http.StatusInternalServerError)
	//	return
	//}
	//
	//dc.Parse()
	//
	//saveFilename := fmt.Sprintf("%v_%v_%v", t.UserID, time.Now().Unix(), t.Filename)
	//err = dc.Execute("./tmp/parsed/"+saveFilename, resp.Data)
	//if err != nil {
	//	h.reportError(w, err, http.StatusInternalServerError)
	//	return
	//}
	//
	//// Send to Yandex Disk
	//
	//err = client.ResourcesUpload(YaDiskData.SaveFolder+"/"+saveFilename, "https://solweb.site/tmp/parsed/"+saveFilename)
	//if err != nil {
	//	h.reportError(w, err, http.StatusInternalServerError)
	//	return
	//}
	//
	//fmt.Println("https://solweb.site/tmp/parsed/" + saveFilename)
}
