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

import org.tio.sitexxx.service.service.jpush.huawei.messaging.HuaweiApp;
import org.tio.sitexxx.service.service.jpush.huawei.util.ValidatorUtils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;

/**
 * <pre>
 *    @author : vagrancy
 *    e-mail : 18050829067@163.com
 *    time   : 2025-02-21 10:21
 *    desc   :
 * </pre>
 */
public abstract class ThreadManager {
    final HonorExecutors getHonorExecutors(HonorApp app) {
        return new HonorExecutors(getExecutor(app));
    }

    final void releaseHonorExecutors(HonorApp app, HonorExecutors executor) {
        releaseExecutor(app, executor.userExecutor);
    }

    /**
     * Returns the main thread pool for an app.
     *
     * @param app A {@link HuaweiApp} instance.
     * @return A non-null <code>ExecutorService</code> instance.
     */
    protected abstract ExecutorService getExecutor(HonorApp app);

    /**
     * Cleans up the thread pool associated with an app.
     * This method is invoked when an app is deleted.
     *
     * @param app A {@link HuaweiApp} instance.
     * @return A non-null <code>ExecutorService</code> instance.
     */
    protected abstract void releaseExecutor(HonorApp app, ExecutorService executor);

    /**
     * Returns the <code>ThreadFactory</code> to be used for creating long-lived threads. This is
     * used mainly to create the long-lived worker threads for the scheduled (periodic) tasks started by the SDK.
     * The SDK guarantees clean termination of all threads started via this <code>ThreadFactory</code>, when the user
     * calls {@link HuaweiApp#delete()}.
     *
     * <p>If long-lived threads cannot be supported in the current runtime, this method may
     * throw a {@code RuntimeException}.
     *
     * @return A non-null <code>ThreadFactory</code>.
     */
    protected abstract ThreadFactory getThreadFactory();

    static final class HonorExecutors {
        private ExecutorService userExecutor;

        private HonorExecutors(ExecutorService userExecutor) {
            ValidatorUtils.checkArgument(userExecutor != null, "ExecutorService must not be null");
            this.userExecutor = userExecutor;
        }
    }

}
