package org.wso2.carbon.device.mgt.ios.core.util;

import org.wso2.carbon.device.mgt.ios.core.bean.ChallengeTokenBean;
import org.wso2.carbon.device.mgt.ios.core.dto.CacheEntry;

import javax.cache.Cache;
import javax.cache.CacheConfiguration;
import javax.cache.CacheManager;
import javax.cache.Caching;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class CommonUtil {

    private static final String TOKEN_CACHE_MANAGER = "TOKEN_CACHE_MANAGER";
    private static final String TOKEN_CACHE = "TOKEN_CACHE";
    private static final long CACHE_DURATION = 15l;
    private static boolean isContextCacheInitialized = false;

    public Date getValidityStartDate() {
        Date targetDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(targetDate);
        calendar.add(Calendar.DATE, -2);

        return calendar.getTime();
    }

    public Date getValidityEndDate() {
        Date targetDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(targetDate);
        calendar.add(Calendar.YEAR, 100);

        return calendar.getTime();
    }

    public static String generateRandomToken() {
        return String.valueOf(UUID.randomUUID());
    }

    public static void persistChallengeToken(ChallengeTokenBean challengeTokenBean) {

        Object objCacheEntry = getCacheEntry(challengeTokenBean.getChallengeToken());
        CacheEntry cacheEntry;
        if (objCacheEntry == null) {
            cacheEntry = new CacheEntry();
            cacheEntry.setUsername(challengeTokenBean.getUsername());
            cacheEntry.setDomain(challengeTokenBean.getDomain());
            cacheEntry.setRefreshToken(challengeTokenBean.getRefreshToken());
            cacheEntry.setAccessToken(challengeTokenBean.getAccessToken());
            cacheEntry.setClientCredentials(challengeTokenBean.getClient());
        } else {
            cacheEntry = (CacheEntry)objCacheEntry;
        }

        cacheEntry.setDeviceID(challengeTokenBean.getDeviceID());

        getTokenCache().put(challengeTokenBean.getChallengeToken(), cacheEntry);
    }

    public static Object getCacheEntry(String token) {
        return getTokenCache().get(token);
    }

    private static Cache getTokenCache() {
        CacheManager contextCacheManager = Caching.getCacheManager(TOKEN_CACHE_MANAGER).
                getCache(TOKEN_CACHE).getCacheManager();

        if (!isContextCacheInitialized) {
            isContextCacheInitialized = true;
            return contextCacheManager.createCacheBuilder(TOKEN_CACHE_MANAGER).setExpiry(
                    CacheConfiguration.ExpiryType.MODIFIED,
                    new CacheConfiguration.Duration(TimeUnit.MINUTES, CACHE_DURATION)).setStoreByValue(false).build();
        } else {
            return Caching.getCacheManager(TOKEN_CACHE_MANAGER).getCache(TOKEN_CACHE);
        }
    }
}
