package util

import (
	"ZhenTuLocalPassiveAdapter/config"
	"fmt"
	"path"
	"regexp"
	"strings"
	"time"
)

func ParseStartStopTime(filePath string, relativeDate time.Time) (time.Time, time.Time, error) {
	_, file := path.Split(filePath)
	split := strings.Split(file, config.Config.FileName.TimeSplit)
	if len(split) == 0 {
		return time.Time{}, time.Time{}, fmt.Errorf("无法解析时间范围")
	}
	startTime, err := ParseTime(split[0], relativeDate)
	if err != nil {
		return time.Time{}, time.Time{}, err
	}
	if len(split) == 1 {
		return startTime, startTime, nil
	}
	stopTime, err := ParseTime(split[1], relativeDate)
	if err != nil {
		return startTime, startTime, nil
	}
	return startTime, stopTime, nil
}

func ParseTime(s string, relativeDate time.Time) (time.Time, error) {
	re := regexp.MustCompile(`(\d{2}).?(\d{2}).?(\d{2})`)
	matches := re.FindStringSubmatch(s)
	if len(matches) != 4 {
		return time.Time{}, fmt.Errorf("无法解析时间范围")
	}
	tm, err := time.Parse("15.04.05", fmt.Sprintf("%s.%s.%s", matches[1], matches[2], matches[3]))
	if err != nil {
		return time.Time{}, err
	}
	return time.Date(relativeDate.Year(), relativeDate.Month(), relativeDate.Day(),
		tm.Hour(), tm.Minute(), tm.Second(), 0, time.Local), nil
}