package org.ccci.gto.android.common.util;

import android.annotation.TargetApi;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.ParallelExecutorCompat;

import org.ccci.gto.android.common.concurrent.NamedThreadFactory;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class AsyncTaskCompat {
    @NonNull
    private static final Compat COMPAT;
    static {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            COMPAT = new GingerbreadCompat();
        } else {
            COMPAT = new HoneycombCompat();
        }
    }

    public static final Executor SERIAL_EXECUTOR = COMPAT.serialExecutor();

    /**
     * @deprecated Since v1.1.2, use {@link ParallelExecutorCompat#getParallelExecutor()} instead.
     */
    @Deprecated
    public static final Executor THREAD_POOL_EXECUTOR = ParallelExecutorCompat.getParallelExecutor();

    public static void execute(@NonNull final Runnable task) {
        COMPAT.execute(task);
    }

    interface Compat {
        void execute(@NonNull Runnable task);

        @NonNull
        Executor serialExecutor();
    }

    static class GingerbreadCompat implements Compat {
        private Executor mExecutor;

        @NonNull
        private synchronized Executor getExecutor() {
            if (mExecutor == null) {
                mExecutor = Executors.newFixedThreadPool(1, new NamedThreadFactory("AsyncTaskCompat"));
                if (mExecutor instanceof ThreadPoolExecutor) {
                    ((ThreadPoolExecutor) mExecutor).setKeepAliveTime(30, TimeUnit.SECONDS);
                    ((ThreadPoolExecutor) mExecutor).allowCoreThreadTimeOut(true);
                }
            }

            return mExecutor;
        }

        @Override
        public void execute(@NonNull final Runnable task) {
            getExecutor().execute(task);
        }

        @NonNull
        @Override
        public Executor serialExecutor() {
            return getExecutor();
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    static class HoneycombCompat extends GingerbreadCompat {
        @Override
        public void execute(@NonNull Runnable task) {
            AsyncTask.execute(task);
        }

        @NonNull
        @Override
        public Executor serialExecutor() {
            return AsyncTask.SERIAL_EXECUTOR;
        }
    }
}

@@ -173,66 +173,8 @@
 ull;
-%0Aimport android.support.v4.content.ParallelExecutorCompat;
 %0A%0Aim
@@ -773,242 +773,8 @@
 );%0A%0A
-    /**%0A     * @deprecated Since v1.1.2, use %7B@link ParallelExecutorCompat#getParallelExecutor()%7D instead.%0A     */%0A    @Deprecated%0A    public static final Executor THREAD_POOL_EXECUTOR = ParallelExecutorCompat.getParallelExecutor();%0A%0A
     

remove deprecated THREAD_POOL_EXECUTOR