package templates

import (
	. "primesys_email/src/models/report"
	. "primesys_email/src/templates/utils"
)

const (
	delayStartGrace = 30 * 60 // seconds after the expected start
	earlyEndGrace   = 28 * 60 // seconds before the expected end
)

func CreateKeyManMidShiftReportExcel(reports []DivisionTripReportModel, divisionName string, reportDate string) ([]byte, error) {
	t := tableReport{
		sheet:   "KeyMan Mid-Shift Report",
		title:   "KEYMAN MID-SHIFT REPORT",
		widths:  []float64{10, 26, 22, 22, 16, 14, 20, 20, 16, 26, 30},
		headers: []string{"Sr.No", "Name", "Expected Location", "Actual Location", "Delay Start", "Early End", "Expected Time", "OnTrack Time", "Actual KM", "Start% - End% Battery", "Remarks"},
	}

	return writeTableReport(t, reports, divisionName, reportDate, func(r DivisionTripReportModel, s tableStyles) []tableCell {
		// expected and actual location both use the actual km, same as the java report
		location := kmRange(r.TripActualStartKm, r.TripActualEndKm, 2)

		return []tableCell{
			{DefaultString(r.DeviceName), s.name},
			{location, s.cell},
			{location, s.cell},
			yesNoCell(delayStart(r.ActualStartTime, r.TripStartTime), s),
			yesNoCell(earlyEnd(r.ActualEndTime, r.TripEndTime), s),
			{timeRange(r.TripStartTime, r.TripEndTime), s.cell},
			{timeRange(r.ActualStartTime, r.ActualEndTime), s.cell},
			{DefaultFloat(r.DistanceCoverTrip), s.cell},
			{batteryText(r.TripList, "- - -"), s.cell},
			{remarkText(r.Remark), s.cell},
		}
	})
}

// delayStart is "Yes" when the actual start is more than 30 minutes after the expected start
func delayStart(actual, expected *int64) string {
	if actual == nil || *actual < 1 {
		return "-"
	}
	if *actual > derefInt64(expected)+delayStartGrace {
		return "Yes"
	}
	return "No"
}

// earlyEnd is "Yes" when the actual end is more than 28 minutes before the expected end
func earlyEnd(actual, expected *int64) string {
	if actual == nil || *actual < 1 {
		return "-"
	}
	if *actual < derefInt64(expected)-earlyEndGrace {
		return "Yes"
	}
	return "No"
}

func derefInt64(value *int64) int64 {
	if value == nil {
		return 0
	}
	return *value
}
