package cn.tee3.manager.util;

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.locks.LockSupport;
import cn.tee3.manager.service.IBaseService;

public class LineAsyncTask implements IBaseService {

    private LineThread lineThread;
    private List<IBaseService> taskList;
    private boolean isStop;
    private boolean isAlive;
    private TaskCompleteListener completeListener;

    private LineAsyncTask() {
    }

    public static LineAsyncTask getInstance() {
        return LineAsyncTask.Builder.INSTANCE;
    }

    private static class Builder {
        private static final LineAsyncTask INSTANCE = new LineAsyncTask();
    }

    @Override
    public String init() {
        isStop = false;
        if (lineThread == null) {
            lineThread = new LineThread();
        }
        return IBaseService.FAILURE;
    }

    @Override
    public void dispose() {
        isStop = true;
        lineThread = null;
        isAlive = false;
        lineThread = null;
    }

    public LineAsyncTask setCompleteListener(TaskCompleteListener listener) {
        this.completeListener = listener;
        return this;
    }

    public void execute(List<IBaseService> taskList) {
        if (taskList.size() == 0) {
            return;
        }
        init();
        this.taskList = taskList;
        if (!isAlive) {
            lineThread.start();
            isAlive = true;
        }
    }

    private class LineThread extends Thread {
        @Override
        public void run() {
            super.run();
            Iterator<IBaseService> iterator = taskList.iterator();
            while (iterator.hasNext()) {
                IBaseService task = iterator.next();
                if (isStop) {
                    break;
                }

                RxSyncTask.getInstance().executeOnMainThread(new RxSyncTask.Action02() {
                    @Override
                    public void onTask() {
                        task.init();
                    }
                });
                if (taskList.indexOf(task) != taskList.size() - 1) {
                    LockSupport.park();
                }
            }

            if (completeListener != null) {
                RxSyncTask.getInstance().executeOnMainThread(new RxSyncTask.Action02() {
                    @Override
                    public void onTask() {
                        completeListener.complete(!isStop);
                    }
                });
            }

            isAlive = false;
            dispose();
        }
    }

    public void wake() {
        if (lineThread != null) {
            LockSupport.unpark(lineThread);
        }
    }

    public void wakeAndStop() {
        if (lineThread != null) {
            LockSupport.unpark(lineThread);
            isStop = true;
        }
    }

    public void stop() {
        isStop = true;
    }

    public interface TaskCompleteListener {
        void complete(boolean isSuccess);
    }
}
