package com.example.repurchase.utils;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Pattern;


public class DateUtils {
    private DateUtils() {
    }

    public static String getOffsetMonth(String yearAndMonth, int offset) {
        if (!Pattern.matches("\\d{4}[/-]\\d{2}", yearAndMonth)) {
            throw new RuntimeException("the format of month is not correct, example 2016-01 or 2016/01");
        }
        int year = Integer.parseInt(yearAndMonth.split("[/-]")[0]);
        int month = Integer.parseInt(yearAndMonth.split("[/-]")[1]);
        String offsetYearAndMonth = "";
        if (offset >= 0) {
            if (offset % 12 == 1 & month == 12) {
                offsetYearAndMonth = String.format("%04d-%02d", year + (offset / 12) + 1, 1);
            } else {
                offsetYearAndMonth = String.format("%04d-%02d", year + (offset / 12), month + offset % 12);
            }
        } else {
            if (offset % 12 == -1 & month == 1) {
                offsetYearAndMonth = String.format("%04d-%02d", (year + (offset / 12) - 1), 12);
            } else {
                offsetYearAndMonth = String.format("%04d-%02d", year + (offset / 12), month + offset % 12);
            }
        }
        return offsetYearAndMonth;
    }

    public static ArrayList<String> getMonthAndYearRange(String startYearAndMonth, String stopYearAndMonth) throws ParseException {
        ArrayList<String> yearAndMonths = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date yearAndMonthBegin = sdf.parse(startYearAndMonth.replace("/", "-"));
        Date yearAndMonthEnd = sdf.parse(stopYearAndMonth.replace("/", "-"));
        if (yearAndMonthEnd.after(new Date())) {
            yearAndMonthEnd = new Date();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(yearAndMonthBegin);
        while (yearAndMonthBegin.compareTo(yearAndMonthEnd) < 0) {
            yearAndMonths.add(sdf.format(yearAndMonthBegin));
            calendar.add(Calendar.MONTH, 1);
            yearAndMonthBegin = calendar.getTime();
        }
        return yearAndMonths;
    }

    public static String getCurrentTime() {
        Date date = new Date(); //获取当前的系统时间。
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //使用了默认的格式创建了一个日期格式化对象。
        String time = dateFormat.format(date); //可以把日期转换转指定格式的字符串
        return time;
    }
}

