package cn.reghao.tnb.common.util;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * @author reghao
 * @date 2022-01-06 13:02:04
 */
public class StringUtil {
    public static String getPubDateStr(LocalDateTime pubDate) {
        LocalDateTime current = LocalDateTime.now();
        Duration duration = Duration.between(pubDate, current);
        long days = duration.toDays();
        long hours = duration.toHours();
        long minutes = duration.toMinutes();
        long seconds = duration.toSeconds();

        String dateStr;
        if (days != 0) {
            if (days > 365) {
                long years = days/365;
                dateStr = String.format("%s 年前", years);
            } else if (days > 30) {
                long months = days/30;
                dateStr = String.format("%s 个月前", months);
            } else if (days > 7) {
                long weeks = days/7;
                dateStr = String.format("%s 周前", weeks);
            } else {
                dateStr = String.format("%s 天前", days);
            }
        } else if (hours != 0) {
            dateStr = String.format("%s 小时前", hours);
        } else if (minutes != 0) {
            dateStr = String.format("%s 分钟前", minutes);
        } else {
            dateStr = String.format("%s 秒钟前", seconds);
        }

        return dateStr;
    }

    public static String getTimeStr(int duration) {
        int hour = duration/3600;
        int minute = 0;
        int second = 0;
        if (hour > 0) {
            int i = duration%3600;
            minute = i/60;
            if (minute > 0) {
                second = i%60;
            } else {
                second = i;
            }
        } else {
            minute = duration/60;
            if (minute > 0) {
                second = duration%60;
            } else {
                second = duration;
            }
        }

        return String.format("%s:%s:%s", getStr(hour), getStr(minute), getStr(second));
    }

    private static String getStr(int value) {
        if (value < 10) {
            return String.format("0%s", value);
        } else {
            return ""+value;
        }
    }

    public static String getObjectName(String objectUrl) {
        String objectUrl1 = objectUrl.replace("//", "");
        int index = objectUrl1.indexOf("/");
        return objectUrl1.substring(index+1);
    }

    public static String getUppercaseLetter(int pos) {
        int ascii = 64 + pos;
        char ch1 = (char)ascii;
        return String.valueOf(ch1);
    }

    /**
     * 返回格式为 .mp4 形式的后缀名
     *
     * @param
     * @return
     * @date 2021-12-08 下午3:32
     */
    public static String getSuffix(String filename) {
        if (filename == null) {
            return "";
        }

        int idx = filename.lastIndexOf(".");
        return idx == -1 ? "" : filename.substring(idx);
    }
}
