package com.usai.util;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.usai.redant.raimage.RedAntApplication;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by ray on 28/06/2017.
 */

public class RAOperationQueue {

    public interface OperationCallback {
        /**
            每个具体任务执行的回调
         */
        public Boolean operate(Bundle taskinfo);
        public void operateFinish(Bundle taskinfo);
    }

    OperationCallback execCallback;
    public void setCallback(OperationCallback callback)
    {
        execCallback=callback;
    }
    //并发队列
    private ConcurrentLinkedQueue<Bundle> queue = new ConcurrentLinkedQueue<Bundle>();
    // 最大并发数
    public int MaxThread = 3;
    //线程池
    private ExecutorService es = Executors.newCachedThreadPool();


//    public RAOperation runThread;
    public void addOperation(final Bundle taskinfo)
    {


        queue.offer(taskinfo);
        while (((ThreadPoolExecutor)es).getActiveCount()< MaxThread) {


            es.submit(new Runnable() {
                boolean wrong = false;
                @Override
                public void run() {

                    while (!queue.isEmpty()) {
                        Bundle task=queue.poll();

                        System.out.println("running  tid="+Thread.currentThread().getId());
                        task.putLong("tid",Thread.currentThread().getId());
//                        int min=1000;
//                        int max=5000;
//                        int sleep=new Random().nextInt(max)%(max-min+1) + min;
//                        try{
//                            Thread.currentThread().sleep(sleep);
//                        }catch(InterruptedException ie){
//                            ie.printStackTrace();
//                        }
                        boolean retry=execCallback.operate(task);
                        if(retry)
                            queue.offer(task);
                        else
                        {
                            task.remove("tid");
                            execCallback.operateFinish(task);

                            RAUploadManager.TaskStatus status= RAUploadManager.TaskStatus.values()[task.getInt("status",0)];

                            if (status== RAUploadManager.TaskStatus.TaskStatusError)
                                wrong=true;

                        }
                        System.out.println("     finish  tid="+Thread.currentThread().getId());
                    }

                    synchronized (this)
                    {
                        if(((ThreadPoolExecutor) es).getActiveCount()==1)
                        {


                            Intent intent = new Intent("REDANT.RAImage.UPLOAD_COMPLETE");




                            if(wrong)
                            {
                                intent.putExtra("result","error");
                            }
                            else
                            {
                                intent.putExtra("result","finish");
                            }

                            RedAntApplication.getInstance().getApplicationContext().sendBroadcast(intent);

                            //getApplicationContext()
                            Log.e("Finish_msg", "run: -----------task finish" );

//                                                        Toast toast = Toast.makeText(getApplicationContext(),
//                                    "Piid must be a number",
//                                    Toast.LENGTH_LONG);
//                            toast.setGravity(Gravity.CENTER, 0, 0);
//                            toast.show();;

                        }
                    }

                }
            });

        }
    }
    public void stopQueue()
    {
        queue.clear();
        es.shutdown();
    }
}
