package ru.yandex.wmtools.common.service;

import org.springframework.beans.factory.annotation.Required;
import ru.yandex.common.util.cache.ObjectProvider;
import ru.yandex.common.util.cache.SimpleCache;
import ru.yandex.wmtools.common.data.info.OAuthInfo;
import ru.yandex.wmtools.common.error.InternalException;

/**
 * @author avhaliullin
 */
public class OAuthCachingService implements OAuthService {
    private SimpleCache<Key, OAuthInfo> cache = new SimpleCache<Key, OAuthInfo>();

    @Override
    public OAuthInfo getOAuthInfo(String token) throws InternalException {
        Key key = new Key(token);
        OAuthInfo res = cache.getData(key);
        if (res==null){
            if (key.getException()==null){
                return null;
            }
                throw key.getException();
        }
        return res;
    }

    @Required
    public void setOAuthService(final OAuthService oAuthService) {
        cache.setObjectProvider(new ObjectProvider<Key, OAuthInfo>() {
            @Override
            public OAuthInfo getData(Key key) {
                try {
                    return oAuthService.getOAuthInfo(key.getKey());
                } catch (InternalException e) {
                    key.setException(e);
                    return null;
                }
            }
        });
    }

    private class Key {
        private final String key;
        private InternalException exception;

        public Key(String key) {
            this.key = key;
        }

        public String getKey() {
            return key;
        }

        public InternalException getException() {
            return exception;
        }

        public void setException(InternalException exception) {
            this.exception = exception;
        }
    }

    public void setActualTimeInSeconds(long seconds) {
        cache.setActualTimeInSeconds(seconds);
    }
}
