package ru.yandex.webmaster.common.tvm;

import java.util.concurrent.TimeUnit;

import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.yandex.webmaster.common.util.RetryUtils;
import ru.yandex.wmtools.common.service.ITVMTicketService;

/**
 * @author: ishalaru
 * DATE: 02.10.2019
 */

public class BlackBoxTVM implements ITVMTicketService {
    private static final Logger log = LoggerFactory.getLogger(BlackBoxTVM.class);
    private static final int TOKEN_TTL = 300;
    private Tvm2TokenService tvm2TokenService;
    private Supplier<String> tokenCache =
            Suppliers.memoizeWithExpiration(this::getTokenFromTvmWithRetry, TOKEN_TTL, TimeUnit.SECONDS);


    public void setTvm2TokenService(Tvm2TokenService tvm2TokenService) {
        this.tvm2TokenService = tvm2TokenService;
    }

    private String getTokenFromTvmWithRetry() {
        try {
            return RetryUtils.query(RetryUtils.instantRetry(5), this::getTokenFromTvm);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        }
    }

    private  String getTokenFromTvm() {
        log.debug("Take token for blackbox");
        return tvm2TokenService.getToken();
    }


    @Override
    public String getTicket() {
        return tokenCache.get();
    }
}
