/*

 Copyright (c) [2023] [pcm]
 [pcm-coordinator] is licensed under Mulan PSL v2.
 You can use this software according to the terms and conditions of the Mulan PSL v2.
 You may obtain a copy of Mulan PSL v2 at:
          http://license.coscl.org.cn/MulanPSL2
 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 EITHER EXPaRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 See the Mulan PSL v2 for more details.

*/

package timeutils

import (
	"time"
)

var timeTemplates = []string{
	"2006-01-02 15:04:05", //常规类型
	"2006/01/02 15:04:05",
	"2006-01-02",
	"2006/01/02",
	"15:04:05",
}

func GetTimeDurationString(startTime string, endTime string) string {
	end, _ := time.Parse("2006-01-02 15:04:05", endTime)
	start, _ := time.Parse("2006-01-02 15:04:05", startTime)
	difference := end.Sub(start)
	return difference.Truncate(time.Second).String()
}

func DurationToDateTime(timeData uint64) time.Time {
	timeString := time.Unix(int64(timeData), 0).Format("2006-01-02 15:04:05")
	return TimeStringToGoTime(timeString)
}

// TimeStringToGoTime 时间格式字符串转换
func TimeStringToGoTime(tm string) time.Time {
	for i := range timeTemplates {
		t, err := time.ParseInLocation(timeTemplates[i], tm, time.Local)
		if nil == err && !t.IsZero() {
			return t
		}
	}
	return time.Time{}
}

func TimeStringRemoveZone(tm string) string {
	timeZone, _ := time.Parse("2006-01-02 15:04:05 -0700 MST", tm)
	return timeZone.Format("2006-01-02 15:04:05")
}

func TimeRemoveZone(tm time.Time) time.Time {
	parse, err := time.Parse("2006-01-02 15:04:05", tm.Format("2006-01-02 15:04:05"))
	if err != nil {
		return time.Time{}
	}
	return parse
}

func StringToUnixTime(str string) int64 {
	dt, err := time.ParseInLocation("2006-01-02 15:04:05", str, time.Local)
	if err != nil {
		return 0
	}
	return dt.Unix()
}

func UnixTimeToString(ut int64) string {
	t := time.Unix(ut, 0)

	return t.Format("2006-01-02 15:04:05")
}
