package utils

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strconv"
)

var holidays []ResHolidays

func CheckHoliday(date string) (bool, string) {
	year, err := strconv.Atoi(date[:4])
	if len(holidays) == 0 {
		err = getHolidays(year)
		if err != nil {
			return false, ""
		}
	}
	for _, holiday := range holidays {
		if date == holiday.Date {
			return true, holiday.HolidayNameCn
		}
	}
	return false, ""
}

func getHolidays(year int) error {
	var res map[string]resHolidaysApi
	//var holidays []ResHolidays
	data, err := http.Get(fmt.Sprintf("https://api.jiejiariapi.com/v1/holidays/%s", strconv.Itoa(year)))
	if err != nil {
		return err
	}
	defer func(Body io.ReadCloser) {
		err = Body.Close()
		if err != nil {
			return
		}
	}(data.Body)
	body, _ := io.ReadAll(data.Body)
	//解析json结构
	err = json.Unmarshal(body, &res)
	if err != nil {
		return err
	}
	for _, j := range res {
		holidays = append(holidays, ResHolidays{
			Date:          j.Date,
			HolidayNameCn: j.Name,
		})
	}
	return nil
}
