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
		BundlesATA12   []types.BundleData
		BundlesATA345  []types.BundleData
		BarcodesATA12  []types.Barcode
		BarcodesATA345 []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
		}
		// get ata12 shift bundles
		bundles12, err := storage.ShiftListBundle(r.Context(), dates[0], dates[1], types.ATA12)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// get ata345 shift bundles
		bundles345, err := storage.ShiftListBundle(r.Context(), dates[0], dates[1], types.ATA345)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// get ata12 shift barcodes
		barcodesATA12, err := storage.ShiftListBarcode(r.Context(), dates[0], dates[1], types.ATA12)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// get ata345 shift barcodes
		barcodesATA345, err := storage.ShiftListBarcode(r.Context(), dates[0], dates[1], types.ATA345)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// create view
		view := &PageView{
			Stats:          &types.Stats{},
			BundlesATA12:   bundles12,
			BundlesATA345:  bundles345,
			BarcodesATA12:  barcodesATA12,
			BarcodesATA345: barcodesATA345,
		}

		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
		}
	}
}
