package com.tzld.piaoquan.recommend.server.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

@Slf4j
public class FestiveUtil {

    private static Map<String, String> festiveMap = new HashMap<>();

    private static Map<String, List<String>> festiveNameAndDateMap = new HashMap<>();

    public static void init() {
        long start = System.currentTimeMillis();
        InputStream resourceAsStream = FestiveUtil.class.getClassLoader().getResourceAsStream("festive.txt");

        if (Objects.nonNull(resourceAsStream)) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(resourceAsStream))) {
                Map<String, String> tmpMap = new HashMap<>();
                Map<String, List<String>> nameAndDateMap = new HashMap<>();
                String line;
                while ((line = reader.readLine()) != null) {
                    String[] split = line.split(",");
                    if (split.length >= 2) {
                        tmpMap.put(split[0], split[1]);

                        List<String> dates = nameAndDateMap.computeIfAbsent(split[1], k -> new ArrayList<>());
                        dates.add(split[0]);
                        nameAndDateMap.put(split[1], dates);
                    }
                }

                FestiveUtil.festiveMap = tmpMap;
                FestiveUtil.festiveNameAndDateMap = nameAndDateMap;
            } catch (IOException e) {
                log.error("read festive.txt error: ", e);
            }
        }

        long end = System.currentTimeMillis();
        log.info("festive.txt loaded successfully cost {}", end - start);
    }

    public static String getFestiveByDate(String date) {
        return festiveMap.get(date);
    }

    public static List<String> getDateByFestiveName(String festiveName) {
        return festiveNameAndDateMap.get(festiveName);
    }
}
