package org.tio.sitexxx.service.service.jpush.honor.messaging;

import org.tio.sitexxx.service.service.jpush.huawei.util.ValidatorUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Future;

/**
 * <pre>
 *    @author : vagrancy
 *    e-mail : 18050829067@163.com
 *    time   : 2025-02-21 10:31
 *    desc   :
 * </pre>
 */
public class TokenRefresher {
    private static final Logger logger = LoggerFactory.getLogger(TokenRefresher.class);

    private HonorApp app;
    private HonorCredential credential;

    private Future future;

    public TokenRefresher(HonorApp app) {
        ValidatorUtils.checkArgument(app != null, "app must not be null");
        this.app = app;
        this.credential = app.getOption().getCredential();
    }

    protected void scheduleNext(Runnable task, long initialDelay, long period) {
        logger.debug("Scheduling next token refresh in {} milliseconds", period);
        try {
            future = app.schedule(task, initialDelay, period);
        } catch (UnsupportedOperationException e) {
            logger.debug("Failed to schedule token refresh event", e);
        }
    }

    /**
     * Schedule a forced token refresh to be executed after a specified period.
     *
     * @param period in milliseconds, after which the token should be forcibly refreshed.
     */
    public void scheduleRefresh(final long period) {
        cancelPrevious();
        scheduleNext(() -> credential.refreshToken(), period, period);
    }

    private void cancelPrevious() {
        if (future != null) {
            future.cancel(true);
        }
    }

    /**
     * Starts the TokenRefresher if not already started. Starts refreshing when token is expired. If no active
     * token is present, or if the available token is expired soon, this will also refresh immediately.
     */
    final synchronized void start() {
        logger.debug("Starting the proactive token refresher");
        String accessToken = credential.getAccessToken();
        long refreshDelay;
        if (accessToken == null || StringUtils.isEmpty(accessToken)) {
            credential.refreshToken();
        }

        refreshDelay = credential.getExpireIn();

        scheduleRefresh(refreshDelay);
    }

    final synchronized void stop() {
        cancelPrevious();
        logger.debug("Stopped the proactive token refresher");
    }
}
