package com.datarecovery.master.utils;

import android.text.format.DateUtils;

import com.atmob.common.data.KVUtils;

public class CounterUtil {

    private static final String COUNTER_PREFIX = "COUNTER_UTIL_";

    private static final String COUNTER_DATE_SUFFIX = "_DATE";

    private CounterUtil() {

    }

    /**
     * 检查并增加计数（当天）
     *
     * @param key        计数器key
     * @param limitTimes 限制次数
     * @return 是否超过限制
     */
    public static boolean checkAndIncrementByDay(String key, int limitTimes) {
        if (key == null || key.isEmpty() || limitTimes == 0) {
            return false;
        }
        long lastTime = KVUtils.getDefault().getLong(COUNTER_PREFIX + key + COUNTER_DATE_SUFFIX, 0L);
        if (DateUtils.isToday(lastTime)) {
            int count = KVUtils.getDefault().getInt(COUNTER_PREFIX + key, 0);
            if (count >= limitTimes) {
                return false;
            } else {
                KVUtils.getDefault().putInt(COUNTER_PREFIX + key, count + 1);
                return true;
            }
        } else {
            KVUtils.getDefault().putLong(COUNTER_PREFIX + key + COUNTER_DATE_SUFFIX, System.currentTimeMillis());
            KVUtils.getDefault().putInt(COUNTER_PREFIX + key, 1);
            return true;
        }
    }

    /**
     * 检查是否超过计数（当天）
     *
     * @param key        计数器key
     * @param limitTimes 限制次数
     * @return 是否超过限制
     */
    public static boolean checkLimitByDay(String key, int limitTimes) {
        if (key == null || key.isEmpty() || limitTimes == 0) {
            return false;
        }
        long lastTime = KVUtils.getDefault().getLong(COUNTER_PREFIX + key + COUNTER_DATE_SUFFIX, 0L);
        if (DateUtils.isToday(lastTime)) {
            int count = KVUtils.getDefault().getInt(COUNTER_PREFIX + key, 0);
            return count < limitTimes;
        }
        return true;
    }

    /**
     * 增加计数器（当天）
     *
     * @param key 计数器key
     */
    public static void incrementByDay(String key) {
        long lastTime = KVUtils.getDefault().getLong(COUNTER_PREFIX + key + COUNTER_DATE_SUFFIX, 0L);
        if (DateUtils.isToday(lastTime)) {
            int count = KVUtils.getDefault().getInt(COUNTER_PREFIX + key, 0);
            KVUtils.getDefault().putLong(COUNTER_PREFIX + key + COUNTER_DATE_SUFFIX, System.currentTimeMillis());
            KVUtils.getDefault().putInt(COUNTER_PREFIX + key, count + 1);
        } else {
            KVUtils.getDefault().putLong(COUNTER_PREFIX + key + COUNTER_DATE_SUFFIX, System.currentTimeMillis());
            KVUtils.getDefault().putInt(COUNTER_PREFIX + key, 1);
        }
    }
}