package handlers

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

	"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 IndexHandler(storage storage.Storager) httprouter.Handle {
	type PageView struct {
		Stats    *types.Stats
		Bundles  []types.BundleData
		Barcodes []types.Barcode
	}
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		// get current shift dates
		dates, err := helper.GetShiftDates(time.Now())
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		//
		bundles, err := storage.ShiftListBundle(r.Context(), dates[0], dates[1])
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// create view
		view := &PageView{
			Stats:    &types.Stats{},
			Bundles:  bundles,
			Barcodes: []types.Barcode{},
		}

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