package handlers

import (
	"fmt"
	"net/http"
	"text/template"

	"git.espin.casa/albert/cml04-falcon-ui/helper"
	"git.espin.casa/albert/cml04-falcon-ui/storage"
	"git.espin.casa/albert/cml04-falcon-ui/types"
	"github.com/julienschmidt/httprouter"
)

func BarcodesHandler(storage storage.Storager) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		// get method
		if r.Method == http.MethodGet {
			// parse template files
			t, _ := template.ParseFiles("templates/base.html", "templates/barcodes.html")
			// execute templates
			err := t.Execute(w, nil)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}
		// post method
		if r.Method == http.MethodPost {
			// barcodes holder
			Barcodes := []types.Barcode{}
			// parse form data from formulary
			if err := r.ParseForm(); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
			// barcode
			codigo := r.FormValue("codigo")
			// date range
			fechas := r.FormValue("fechas")
			// get range dates
			inicio, final, err := helper.Dates(fechas)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			// loading bed
			evacuadores := r.FormValue("evacuadores")
			// check form values
			if codigo != "" {
				// call storager
				data, err := storage.Barcode(r.Context(), codigo)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
				// append barcode to holder
				Barcodes = append(Barcodes, *data)
			} else {
				// get loading bed from string
				lb, ok := types.MapLoadingBed[evacuadores]
				// if loading bed not found
				if !ok {
					http.Error(w, fmt.Errorf("loading bed value not found").Error(), http.StatusInternalServerError)
					return
				}
				// call storager
				data, err := storage.ListBarcode(r.Context(), lb, inicio, final)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
				//set barcodes
				Barcodes = data
			}
			// parse template files
			t, _ := template.ParseFiles("templates/base.html", "templates/barcodes.html")
			// execute templates
			if err := t.Execute(w, Barcodes); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}
	}
}
