package helper

import (
	"fmt"
	"strings"
	"time"
)

func Dates(dr string) (start, finish time.Time, err error) {
	// split string in dates
	inicio := strings.Split(dr, "-")[0]
	final := strings.Split(dr, "-")[1]
	// remove spaces from strings
	inicio = strings.TrimSpace(inicio)
	final = strings.TrimSpace(final)
	// parse start date
	start, err = time.ParseInLocation("02/01/2006 15:04", inicio, time.Local)
	if err != nil {
		return time.Time{}, time.Time{}, err
	}
	// parse finish date
	finish, err = time.ParseInLocation("02/01/2006 15:04", final, time.Local)
	if err != nil {
		return time.Time{}, time.Time{}, err
	}
	return
}

func GetShiftDates(inputTime time.Time) ([]time.Time, error) {
	if inputTime.Hour() >= 6 && inputTime.Hour() < 14 {
		// First shift: 6 to 14 hours
		startTime := time.Date(inputTime.Year(), inputTime.Month(), inputTime.Day(), 6, 0, 0, 0, inputTime.Location())
		endTime := time.Date(inputTime.Year(), inputTime.Month(), inputTime.Day(), 14, 0, 0, 0, inputTime.Location())

		return []time.Time{startTime, endTime}, nil
	} else if inputTime.Hour() >= 14 && inputTime.Hour() < 22 {
		// Second shift: 14 to 22 hours
		startTime := time.Date(inputTime.Year(), inputTime.Month(), inputTime.Day(), 14, 0, 0, 0, inputTime.Location())
		endTime := time.Date(inputTime.Year(), inputTime.Month(), inputTime.Day(), 22, 0, 0, 0, inputTime.Location())

		return []time.Time{startTime, endTime}, nil
	} else if inputTime.Hour() >= 22 || inputTime.AddDate(0, 0, 1).Hour() < 6 {
		// Third shift: 22 hours to 6 next day
		startTime := time.Date(inputTime.Year(), inputTime.Month(), inputTime.Day(), 22, 0, 0, 0, inputTime.Location())
		endTime := time.Date(inputTime.AddDate(0, 0, 1).Year(), inputTime.AddDate(0, 0, 1).Month(), inputTime.AddDate(0, 0, 1).Day(), 6, 0, 0, 0, inputTime.Location())

		return []time.Time{startTime, endTime}, nil
	} else {
		return nil, fmt.Errorf("el horario de entrada no es válido")
	}
}
