package main

import (
	"bytes"
	"fmt"
	"net/http"
	"strconv"
	"strings"

	"brainminder.speedtech.it/internal/request"
	"brainminder.speedtech.it/internal/response"
	"brainminder.speedtech.it/internal/validator"
	"brainminder.speedtech.it/models"
	"github.com/alexedwards/flow"
)

type quicknoteForm struct {
	Id            int64               `form:"Id"`
	Note          string              `form:"Note"`
	Note_rendered string              `form:"Note_rendered"`
	Validator     validator.Validator `form:"-"`
}

type quicknoteTransformForm struct {
	Title            string   `form:"Title"`
	Type_id          int64    `form:"Type_id"`
	Description      string   `form:"Description"`
	Tags             string   `form:"Tags"`
	Categories       []string `form:"Categories"`
	Notebooks        []string `form:"Notebooks"`
	Keep_in_quickbox int      `form:"Keep_in_quickbox"`
}

func (app *application) quickboxAll(w http.ResponseWriter, r *http.Request) {
	var fullBuf = new(bytes.Buffer)

	data := app.newTemplateData(r)

	quicknoteModel := &models.QuicknoteModel{BaseModel: &models.BaseModel{DB: app.db}}

	params := r.URL.Query()
	offset_str := params.Get("offset")
	var offset int64 = 0
	if len(offset_str) == 0 {
		offset = 0
	} else {
		offset, _ = strconv.ParseInt(offset_str, 10, 64)
	}
	data["offset"] = offset

	rows, _, _ := quicknoteModel.AllQB(offset)
	data["quicknotes"] = rows

	err := response.HXFragment(fullBuf, []string{"quickbox/list.tmpl"}, "quickbox:list", data)
	if err != nil {
		app.serverError(w, r, err)
	}
	fullBuf.WriteTo(w)
	w.WriteHeader(http.StatusOK)
}

func (app *application) quickboxAdd(w http.ResponseWriter, r *http.Request) {
	quicknoteModel := models.NewQuicknoteModel(app.db)
	var fullBuf = new(bytes.Buffer)
	var quicknote_id int64
	data := app.newTemplateData(r)

	var quicknoteFromForm quicknoteForm

	err := request.DecodePostForm(r, &quicknoteFromForm)
	if err != nil {
		app.serverError(w, r, err)
	}

	quicknote := &models.Quicknote{
		Note: quicknoteFromForm.Note,
	}

	quicknote_id, err = quicknoteModel.Create(quicknote)
	if err != nil {
		app.badRequest(w, err)
		return
	}

	data["quicknote"] = quicknoteForm{
		Id:            quicknote_id,
		Note:          quicknote.Note,
		Note_rendered: quicknote.Note_rendered,
	}

	err = response.HXFragment(fullBuf, []string{"quickbox/add.tmpl"}, "quickbox:add", data)
	if err != nil {
		app.serverError(w, r, err)
		return
	}

	w.Header().Add("HX-Trigger", `{"quickboxNoteClear": ""}`)

	fullBuf.WriteTo(w)
	w.WriteHeader(http.StatusUnprocessableEntity)
}

func (app *application) quickboxTransform(w http.ResponseWriter, r *http.Request) {
	quicknoteModel := models.NewQuicknoteModel(app.db)
	quicknote_id_str := flow.Param(r.Context(), "quicknote_id")
	quicknote_id, _ := strconv.ParseInt(quicknote_id_str, 10, 64)
	quicknote, _, _ := quicknoteModel.One(quicknote_id)

	data := app.newTemplateData(r)

	var fullBuf = new(bytes.Buffer)

	switch r.Method {
	case http.MethodGet:

		data["quicknote"] = quicknoteForm{
			Id:   quicknote.Id,
			Note: quicknote.Note,
		}

		data["categories"] = app.getCategoriesAsOptions()
		data["categoriesMap"] = app.getCategoriesAsMap()
		data["types"] = app.getTypesAsOptions(r)
		data["notebooks"] = app.getNotebooksAsOptions()

		err := response.HXFragment(fullBuf, []string{"quickbox/transform.tmpl"}, "page:content", data)
		if err != nil {
			app.serverError(w, r, err)
		}

		w.Header().Add("HX-Trigger-After-Settle", `{"showModalDialog": ""}`)
		fullBuf.WriteTo(w)

	case http.MethodPost:
		itemModel := models.NewItemModel(app.db)
		var quicknoteTransformFromForm quicknoteTransformForm

		err := request.DecodePostForm(r, &quicknoteTransformFromForm)
		if err != nil {
			app.serverError(w, r, err)
		}

		item := &models.Item{
			Type_id:     quicknoteTransformFromForm.Type_id,
			Title:       quicknoteTransformFromForm.Title,
			Description: quicknoteTransformFromForm.Description,
			Tags:        quicknoteTransformFromForm.Tags,
		}

		notebooks_str := strings.Join(quicknoteTransformFromForm.Notebooks, "|")
		if len(notebooks_str) > 0 {
			notebooks_str = "|" + notebooks_str + "|"
		}
		item.Notebooks = notebooks_str

		categories_str := strings.Join(quicknoteTransformFromForm.Categories, "|")
		if len(categories_str) > 0 {
			categories_str = "|" + categories_str + "|"
		}
		item.Categories = categories_str

		item_id, err := itemModel.Create(item)
		item.Id = item_id

		typeModel := &models.TypeModel{DB: app.db}
		aType, _, _ := typeModel.One(item.Type_id)
		item.Type_title = aType.Title

		fieldModel := &models.FieldModel{DB: app.db}
		fields, _, _ := fieldModel.ByType(int64(item.Type_id))
		fieldsValues := make(map[int64]map[int]string)

		itemModel.SaveKeywords(item, &fields, fieldsValues)

		if err != nil {
			app.badRequest(w, err)
			return
		}

		data["messageType"] = "success"
		data["messageContent"] = "Quicknote transformed successfully"
		err = response.HXFragment(fullBuf, []string{"partials/message.tmpl"}, "message", data)
		if err != nil {
			app.serverError(w, r, err)
		}

		triggerResponse := fmt.Sprintf(`{"closeQuickboxTransformModal":{"quickNoteId": "%d", "keepQuickNote": "%d"}}`, quicknote_id, quicknoteTransformFromForm.Keep_in_quickbox)
		w.Header().Add("HX-Trigger-After-Settle", triggerResponse)
		fullBuf.WriteTo(w)

		w.WriteHeader(http.StatusUnprocessableEntity)
	}
}

func (app *application) quickboxUpdate(w http.ResponseWriter, r *http.Request) {
	quicknoteModel := models.NewQuicknoteModel(app.db)
	quicknote_id_str := flow.Param(r.Context(), "quicknote_id")
	quicknote_id, _ := strconv.ParseInt(quicknote_id_str, 10, 64)
	quicknote, _, _ := quicknoteModel.One(quicknote_id)

	data := app.newTemplateData(r)
	data["formAction"] = "/quicknote/update/" + quicknote_id_str
	data["formTarget"] = "#message"
	data["messageType"] = ""
	data["messageContent"] = ""

	var fullBuf = new(bytes.Buffer)

	switch r.Method {
	case http.MethodGet:

		data["quicknote"] = quicknoteForm{
			Id:   quicknote.Id,
			Note: quicknote.Note,
		}

		if r.Header.Get("HX-Request") == "true" {

			buf, err := response.Fragment([]string{"quicknotes/form.tmpl", "partials/message.tmpl"}, "page:content", data)
			if err != nil {
				app.serverError(w, r, err)
			}
			fullBuf.Write(buf.Bytes())

			fullBuf.WriteString("<div hx-swap-oob=\"true\" id=\"page-title\">")
			buf, err = response.Fragment([]string{"quicknotes/update_title.tmpl"}, "page:title", data)
			if err != nil {
				app.serverError(w, r, err)
			}
			fullBuf.Write(buf.Bytes())
			fullBuf.WriteString("</div>")

			fullBuf.WriteTo(w)
		} else {
			err := response.Page(w, http.StatusOK, data, []string{"quicknotes/update_title.tmpl", "quicknotes/form.tmpl", "partials/message.tmpl"})
			if err != nil {
				app.serverError(w, r, err)
			}
		}

	case http.MethodPost:
		var quicknoteFromForm quicknoteForm

		err := request.DecodePostForm(r, &quicknoteFromForm)
		if err != nil {
			app.serverError(w, r, err)
		}

		quicknote.Note = quicknoteFromForm.Note

		err = quicknoteModel.Update(quicknote)
		if err != nil {
			app.badRequest(w, err)
			return
		}

		data["quicknote"] = quicknoteForm{
			Id:   quicknote.Id,
			Note: quicknote.Note,
		}

		data["messageType"] = "success"
		data["messageContent"] = "Quicknote saved successfully"

		buf, err := response.Fragment([]string{"partials/message.tmpl"}, "message", data)
		if err != nil {
			app.serverError(w, r, err)
		}
		fullBuf.Write(buf.Bytes())

		fullBuf.WriteString("<div hx-swap-oob=\"true\" id=\"page-title\">")
		buf, err = response.Fragment([]string{"quicknotes/update_title.tmpl"}, "page:title", data)
		if err != nil {
			app.serverError(w, r, err)
		}
		fullBuf.Write(buf.Bytes())
		fullBuf.WriteString("</div>")

		fullBuf.WriteString("<div hx-swap-oob=\"true\" id=\"current_quicknote_id\">")
		buf, err = response.Fragment([]string{"partials/quicknotes-list.tmpl"}, "partial:quicknotes-list", data)
		if err != nil {
			app.serverError(w, r, err)
		}
		fullBuf.Write(buf.Bytes())
		fullBuf.WriteString("</div>")

		fullBuf.WriteTo(w)

		w.WriteHeader(http.StatusUnprocessableEntity)
	}
}

func (app *application) quickboxDelete(w http.ResponseWriter, r *http.Request) {
	quicknoteModel := models.NewQuicknoteModel(app.db)
	quicknote_id_str := flow.Param(r.Context(), "quicknote_id")
	quicknote_id, _ := strconv.ParseInt(quicknote_id_str, 10, 64)

	_, err := quicknoteModel.Delete(quicknote_id)
	if err != nil {
		app.serverError(w, r, err)
	}
}
