package com.usai.redant.raimage.UploadList;

import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.usai.redant.raimage.R;
import com.usai.redant.raimage.UploadService;
import com.usai.util.RAUploadManager;

import java.util.ArrayList;

//import com.usai.redant.raimage.UploadList.swipemenulistview.SwipeMenu;
//import com.usai.redant.raimage.UploadList.swipemenulistview.SwipeMenuCreator;
//import com.usai.redant.raimage.UploadList.swipemenulistview.SwipeMenuItem;
//import com.usai.redant.raimage.UploadList.swipemenulistview.SwipeMenuListView;

public class UploadListActivity extends AppCompatActivity {


    private ArrayList<Bundle> displaylist = new ArrayList<Bundle>();

    //    private SwipeMenuListView uploadList;
    private ListView uploadList;
    private uploadAdapter adapter;
//    private ArrayList<Bundle> arr;

    private RAUploadManager uploadManager;
    private UploadService.MyBinder binder;
    private UploadService uploadServiceservice;
    private boolean serviceConnectionFlag = false; // 绑定服务标识
    private ServiceConnection serviceConnection;
    private RAUploadManager.UIUpdateListener uiUpdateListener = new RAUploadManager.UIUpdateListener() {
//        @Override
//        public void onProgress(long index, double percentage) {
//
//
//            if(true)
//            return;
//
//            final int position = (int)index;
//            final double progress = percentage;
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    Log.d("_LIST", "UploadImage onProgress: " + progress);
//                    long timeStart = System.currentTimeMillis();
////            Object item = uploadList.getItemAtPosition((int) index);
//                    int startShowIndex = uploadList.getFirstVisiblePosition();
//                    int lastShowIndex = uploadList.getLastVisiblePosition();
//
//                    if (position >= startShowIndex && position <= lastShowIndex) {
//                        View cell = uploadList.getChildAt((int)position - startShowIndex);
//                        uploadAdapter.ViewHolder holder= (uploadAdapter.ViewHolder)cell.getTag();
//                        holder.progressBar.setProgress((int) (100 * progress));
//                        holder.progress_tv.setText(String.format("%.1f%%",progress * 100));
//                    }
//
//                    Log.d("_LIST", "UploadImage onProgress: end" + (System.currentTimeMillis() - timeStart));
//                }
//            });
//
//        }

        @Override
        public void updateCell(long index, final Bundle taskinfo)
        {
            if(true)
                return;

            if(true) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        adapter.notifyDataSetChanged();
                    }
                });

                return;
            }

            final int position = (int)index;
//            final double progress = arr.get(position).getDouble("progress");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    double percent = taskinfo.getDouble("progress",0);

//                    Log.d("_synchronized", "UploadImage onProgress: " + percent);
                    long timeStart = System.currentTimeMillis();

//            Object item = uploadList.getItemAtPosition((int) index);
                    int startShowIndex = uploadList.getFirstVisiblePosition();
                    int lastShowIndex = uploadList.getLastVisiblePosition();

                    if (position >= startShowIndex && position <= lastShowIndex) {
                        View cell = uploadList.getChildAt((int)position - startShowIndex);
                        uploadAdapter.ViewHolder holder= (uploadAdapter.ViewHolder)cell.getTag();
//                        holder.progressBar.setProgress((int) (100 * progress));
//                        holder.progress_tv.setText(String.format("%.1f%%",progress * 100));


                        RAUploadManager.TaskStatus istatus = RAUploadManager.TaskStatus.values()[taskinfo.getInt("status",0)];
                        String status="";
                        switch(istatus)
                        {
                            case TaskStatusStart:
                                status="uploading";
                                break;
                            case TaskStatusStop:
                                status="stop";
                                break;
                            case TaskStatusError:
                                status="warning";
                                break;
                            case TaskStatusWait:
                                status="waiting";
                                break;
                            case TaskStatusFinish:
                                status="finish";
                                break;

                            default:
                                status="warning";
                                break;
                        }


                        Log.d("_LIST", "uploadlist UI update POSITION"+position +"    PROGRESS"+ percent*100);

                        String err = taskinfo.getString("msg");
                        String name = taskinfo.getString("file","");
                        holder.name_tv.setText(name);
                        holder.progressBar.setProgress((int)(100 *percent));
                        holder.state_tv.setText(status);

                        holder.progress_tv.setText(String.format("%.2f%%",100*percent));
                        holder.err_tv.setText(err);
                    }

                    Log.d("_LIST", "uploadlist UI: COST" + (System.currentTimeMillis() - timeStart));
                }
            });
        }
        @Override
//        public void updateList()
        public void updateList(final ArrayList<Bundle> newlist)
        {


            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Log.d("_LIST","running  tid="+Thread.currentThread().getId());
                    Log.d("_LIST", "uploadlist UI  size:  "+ newlist.size());
                    long timeStart = System.currentTimeMillis();
                    displaylist = (ArrayList<Bundle>) newlist.clone();
                    adapter.notifyDataSetChanged();


                    Log.d("_LIST", "uploadlist UI: COST" + (System.currentTimeMillis() - timeStart));
                }
            });

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_list);

        ActionBar mActionBar = getSupportActionBar();
        mActionBar.setHomeButtonEnabled(true);
        mActionBar.setDisplayHomeAsUpEnabled(true);
        mActionBar.setTitle("RA Image");


        // 初始化视图
//        uploadList = (SwipeMenuListView)findViewById(R.id.upload_list);
        uploadList = (ListView)findViewById(R.id.upload_list);
        adapter = new uploadAdapter(R.layout.upload_list_cell);
        uploadList.setAdapter(adapter);
        serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                serviceConnectionFlag = true;

                binder = (UploadService.MyBinder)service;
                uploadServiceservice = binder.getService();




                uploadManager = uploadServiceservice.uploadManager;
                uploadManager.uiUpdateListener = uiUpdateListener;
                displaylist = (ArrayList<Bundle>) uploadManager.get_arr_queue().clone(); //uploadManager.arr_queue;



//                adapter.notifyDataSetChanged();
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        adapter = new uploadAdapter(R.layout.upload_list_cell);
//                        uploadList.setAdapter(adapter);
//                    }
//                });
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                serviceConnectionFlag = false;
                uploadManager.uiUpdateListener = null;
            }
        };

        bindService();

//        SwipeMenuCreator creator = new SwipeMenuCreator() {
//
//            @Override
//            public void create(SwipeMenu menu) {
//                // Create different menus depending on the view type
//                switch (menu.getViewType()) {
//                    case 0: {
//                        createRemoveMenuItem(menu);
//                    }
//                    break;
//                    case 1: {
//                        createStartMenuItem(menu);
//                        createRemoveMenuItem(menu);
//                    }
//                    break;
//                    case 2: {
//                        createStartMenuItem(menu);
//                    }
//                    break;
//                    case 3: {
//
//                    }
//                    break;
//                }
//            }
//        };
//
//        uploadList.setMenuCreator(creator);
//
//        uploadList.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
//            @Override
//            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
//                // action
//                Bundle item = arr.get(position);
//                int type = taskSwipeType(position);
//                switch (type) {
//                    case 0: {
//                        if (index == 0) {
//                            // remove
//                            if (serviceConnectionFlag == true && uploadServiceservice != null) {
//                                uploadManager.removeTask(item);
//                            }
//
//                        }
//                    }
//                    break;
//                    case 1: {
//                        if (index == 0) {
//                            // start
//                            if (serviceConnectionFlag == true && uploadServiceservice != null) {
//                                uploadManager.startTask(item);
//                            }
//
//                        } else if (index == 1) {
//                            // remove
//                            if (serviceConnectionFlag == true && uploadServiceservice != null) {
//                                uploadManager.removeTask(item);
//                            }
//
//                        }
//                    }
//                    break;
//                    case 2: {
//                        if (index == 0) {
//                            // start
//                            if (serviceConnectionFlag == true && uploadServiceservice != null) {
//                                uploadManager.startTask(item);
//                            }
//
//                        }
//                    }
//                    break;
//                    case 3: {
//
//                    }
//                    break;
//                }
//
//                return false;
//            }
//        });
    }

//    private void createRemoveMenuItem(SwipeMenu menu) {
//        SwipeMenuItem openItem = new SwipeMenuItem(getApplicationContext());
//        // set item background
//        openItem.setBackground(new ColorDrawable(Color.rgb(0x9b, 0xbf,0x5a)));
//        // set item width
//        openItem.setWidth(dp2px(90));
//        // set item title
//        openItem.setTitle("Remove");
//        // set item title fontsize
//        openItem.setTitleSize(18);
//        // set item title font color
//        openItem.setTitleColor(Color.WHITE);
//        // add to menu
//        menu.addMenuItem(openItem);
//    }
//
//    private void createStartMenuItem(SwipeMenu menu) {
//        SwipeMenuItem openItem = new SwipeMenuItem(getApplicationContext());
//        // set item background
//        openItem.setBackground(new ColorDrawable(Color.rgb(0xff, 0x99,0x33)));
//        // set item width
//        openItem.setWidth(dp2px(90));
//        // set item title
//        openItem.setTitle("Restart");
//        // set item title fontsize
//        openItem.setTitleSize(18);
//        // set item title font color
//        openItem.setTitleColor(Color.WHITE);
//        // add to menu
//        menu.addMenuItem(openItem);
//    }

    @Override
    protected void onDestroy() {

        unbindService(serviceConnection);

        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.upload_list_menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home: {
                finish();
            }
            break;
            case R.id.clear_upload_list_btn: {
//                for(int i=0;i<10;i++)
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//
//                        Log.d("_LIST","running  tid="+Thread.currentThread().getId());
//                        Log.d("_LIST", "uploadlist UI  size:  "+ displaylist.size());
//                        long timeStart = System.currentTimeMillis();
////                        displaylist = (ArrayList<Bundle>) newlist.clone();
//                        adapter.notifyDataSetChanged();
//
//
//                        Log.d("_LIST", "uploadlist UI: COST" + (System.currentTimeMillis() - timeStart));
//                    }
//                });
                clearUploadList();
            }
            break;
        }
        return true;
    }

    private void clearUploadList() {
        if (displaylist.size() == 0) {
            new AlertDialog.Builder(this)
                    .setTitle("Warning")
                    .setMessage("Upload list is empty.")
                    .setPositiveButton("OK",null)
                    .show();
            return;
        }

        new AlertDialog.Builder(this)
                .setTitle("Clear upload list")
                .setMessage("Are you sure remove all error/finish task?")
                .setPositiveButton("YES", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // clear
                        if (serviceConnectionFlag == true && uploadServiceservice != null) {
                            uploadManager.clearTask();
//                            adapter.notifyDataSetChanged();
                        }

                    }
                })
                .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .show();

    }

//
//    private int taskSwipeType(int position) {
//        Bundle item = arr.get(position);
////        Bundle taskinfo = item.getBundle("params");
//        RAUploadManager.TaskStatus istatus = RAUploadManager.TaskStatus.values()[item.getInt("status",0)];
//        int type = 3;
//        switch(istatus)
//        {
//            case TaskStatusWait:
//            case TaskStatusStart:
//                type = 3;
//                break;
//            case TaskStatusStop:
//                type = 2;
//                break;
//            case TaskStatusError:
//                type = 1;
//                break;
//            case TaskStatusFinish:
//                type = 0;
//                break;
//            default:
//                type = 3;
//                break;
//        }
//        return type;
//    }

    private class uploadAdapter extends BaseAdapter {
        private int resourceId;
        public uploadAdapter(int resourceID) {

            resourceId = resourceID;
        }

        @Override
        public int getCount() {
            return displaylist.size();
        }

        @Override
        public Bundle getItem(int position) {
            return displaylist.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

//        @Override
//        public int getViewTypeCount() {
//            return 4;
//        }
//
//        @Override
//        public int getItemViewType(int position) {
//            /**
//             * 0. <finish>      remove              </finish>
//             * 1. <error>       start  remove       </error>
//             * 2. <stop>        start               </stop>
//             * 3. <start\wait>  none                </start\wait>
//             * */
//            return taskSwipeType(position);
//        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

            Log.d("_LIST","running  tid="+Thread.currentThread().getId());
            long timeStart = System.currentTimeMillis();

            final Bundle item = displaylist.get(position);
//            Bundle taskinfo = item.getBundle("params");
//            String barcode = taskinfo.getString("barcode");

            RAUploadManager.TaskStatus istatus = RAUploadManager.TaskStatus.values()[item.getInt("status",0)];
            String status="";
            switch(istatus)
            {
                case TaskStatusStart:
                    status="uploading";
                    break;
                case TaskStatusStop:
                    status="stop";
                    break;
                case TaskStatusError:
                    status="warning";
                    break;
                case TaskStatusWait:
                    status="waiting";
                    break;
                case TaskStatusFinish:
                    status="finish";
                    break;

                default:
                    status="warning";
                    break;
            }
            double percent = item.getDouble("progress",0);
            String err = item.getString("msg");
            String name = item.getString("file","");

            View cell;
            ViewHolder holder;
            if (convertView != null) {

                cell = convertView;
                holder = (ViewHolder)cell.getTag();
                Log.d("_LIST", "getView: " + holder);

            } else  {
//                cell = LayoutInflater.from(getApplicationContext()).inflate(resourceId,null);
                cell = View.inflate(getApplicationContext(),resourceId,null);
                holder = new ViewHolder();
                holder.name_tv = (TextView)cell.findViewById(R.id.upload_name_tv);
                holder.progressBar = (ProgressBar)cell.findViewById(R.id.upload_progressBar);
                holder.state_tv = (TextView)cell.findViewById(R.id.upload_state_tv);
                holder.progress_tv = (TextView)cell.findViewById(R.id.upload_progress_tv);
                holder.err_tv = (TextView)cell.findViewById(R.id.upload_err_tv);
                holder.btn_reload=(ImageButton) cell.findViewById(R.id.btn_reload);


                holder.btn_reload.setImageResource(R.drawable.ic_action_reload);
                if(istatus!= RAUploadManager.TaskStatus.TaskStatusError)
                {
                    holder.btn_reload.setVisibility(View.GONE);
                }
                else
                {
                    holder.btn_reload.setVisibility(View.VISIBLE);
                    holder.btn_reload.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            uploadManager.startTask(item);

                        }
                    });
                }
                cell.setTag(holder);
            }

            holder.name_tv.setText(name);
//            holder.progressBar.setProgress(100 *(int)percent);
            holder.progressBar.setProgress((int) (100 * percent));
            holder.state_tv.setText(status);
//            holder.progress_tv.setText(100*percent+"%");
            holder.progress_tv.setText(String.format("%.2f%%",100*percent));
            holder.err_tv.setText(err);



            Log.d("_LIST", "getView(): POSITION   "+position+" COST   " + (System.currentTimeMillis() - timeStart));
            return cell;
        }

        private class ViewHolder {
            public TextView name_tv;
            public ProgressBar progressBar;
            public TextView state_tv;
            public TextView progress_tv;
            public TextView err_tv;
            public ImageButton btn_reload;
        }
    }


    /** Service */
    private void bindService() {
        Intent intent = new Intent(UploadListActivity.this, UploadService.class);

        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,getResources().getDisplayMetrics());
    }
}
