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 BundleHandler(storage storage.Storager) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {

		if r.Method == http.MethodGet {
			t, _ := template.ParseFiles("templates/base.html", "templates/bundle.html")
			err := t.Execute(w, nil)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}

		// post method
		if r.Method == http.MethodPost {
			// bundles holder
			Bundles := []types.BundleData{}
			// parse form data from formulary
			if err := r.ParseForm(); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
			}
			// ua
			codigo := r.FormValue("ua")
			// date range
			fechas := r.FormValue("fechas")
			// loading bed
			evacuadores := r.FormValue("evacuadores")
			// checkbox value
			onoff := r.FormValue("confirmed")
			// confirmed
			confirmed := false
			if onoff == "on" {
				confirmed = true
			}
			// check form values
			if codigo != "" {
				// call storager
				data, err := storage.Bundle(r.Context(), codigo)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
				// append barcode to holder
				Bundles = append(Bundles, *data)
			} else {
				// get range dates
				inicio, final, err := helper.Dates(fechas)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
				// 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.ListBundle(r.Context(), lb, inicio, final, confirmed)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
				//set barcodes
				Bundles = data
			}
			// parse template files
			t, _ := template.ParseFiles("templates/base.html", "templates/bundle.html")
			// execute templates
			if err := t.Execute(w, Bundles); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}
	}
}
