package com.usai.redant.raimage;

import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.LayoutRes;
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.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.usai.redant.redantmobile.R;
import com.usai.redant.redantmobile.RedAntApplication;
import com.usai.redant.util.RAUploadManager;
import com.usai.redant.util.dbgUtil;

import java.util.ArrayList;
import java.util.Collections;

//import android.support.v7.widget.ListViewCompat;

public class TaskActivity extends AppCompatActivity {

    ArrayList<Bundle> task_arr= new ArrayList<>();
    ListView tasklist;


    private RAUploadManager uploadManager;


    private UploadService.MyBinder binder;
    private UploadService uploadServiceservice;
    private ServiceConnection serviceConnection;

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


//设置返回键
        ActionBar mActionBar = getSupportActionBar();
        mActionBar.setHomeButtonEnabled(true);
        mActionBar.setDisplayHomeAsUpEnabled(true);
        mActionBar.setTitle("RA Image");





        tasklist = (ListView)findViewById(R.id.task_list);

        tasklist.setAdapter(new TaskAdapter(this,R.layout.upload_list_cell/*,task_arr*/));




        serviceConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {


                Log.d("_LIST","-------connected service  tid="+ Thread.currentThread().getId());
                serviceConnectionFlag = true;

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

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

                Collections.reverse(task_arr);
                final TaskAdapter adapter = (TaskAdapter)tasklist.getAdapter();

                adapter.notifyDataSetChanged();


                uploadManager.uiUpdateListener = new RAUploadManager.UIUpdateListener() {
                    @Override
                    public void updateCell(long index, Bundle taskinfo) {
                        if(true) {

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

                                    adapter.notifyDataSetChanged();
                                }
                            });

                            return;
                        }

                    }

                    @Override
                    public void updateList(final ArrayList<Bundle> newlist) {
                        if(true) {

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    task_arr = (ArrayList<Bundle>) newlist.clone();
                                    Collections.reverse(task_arr);
                                    adapter.notifyDataSetChanged();
                                }
                            });

                            return;
                        }

                    }
                };


//                tasklist.getAdapter().no.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();

    }

    @Override
    protected void onDestroy() {

        unbindService(serviceConnection);

        super.onDestroy();
    }


    private void bindService() {
        Intent intent = new Intent(TaskActivity.this, UploadService.class);

        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }
    @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 (task_arr.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();

    }
    class TaskAdapter extends ArrayAdapter
    {

        public TaskAdapter(@NonNull Context context, @LayoutRes int resource/*, @NonNull ArrayList<Bundle> objects*/) {
            super(context, resource/*, objects*/);
        }

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

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

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

            final Bundle item = task_arr.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",(double)item.getDouble("progress",0.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(), R.layout.upload_list_cell, 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);
                cell.setTag(holder);
            }
                holder.btn_reload.setImageResource(R.drawable.ic_action_reload);
                if(istatus!= RAUploadManager.TaskStatus.TaskStatusError&& istatus!= RAUploadManager.TaskStatus.TaskStatusStop)
                {
                    holder.btn_reload.setVisibility(View.GONE);
                }
                else
                {
                    holder.btn_reload.setVisibility(View.VISIBLE);
                    Log.d("_LIST", "new listener: position" + position);
                    holder.btn_reload.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {


                            Bundle task = task_arr.get(position);

                            Log.d("_LIST", "retry: " + task.getString("file","file is null") +"position" + position);



//                            boolean canstart = true;

                            ConnectivityManager connManager = (ConnectivityManager) RedAntApplication.getInstance()
                                    .getSystemService(Context.CONNECTIVITY_SERVICE);

                            NetworkInfo networkInfo = connManager
                                    .getActiveNetworkInfo();
                            if (networkInfo == null)
                            {
                                dbgUtil.Logd(
                                        "Current Network info",
                                        "can not get Active NetworkInfo!");
//                                canstart = false;
                                Toast toast = Toast.makeText(getApplicationContext(),
                                        "No available network. Please try upload manually later.",
                                        Toast.LENGTH_LONG);
                                toast.setGravity(Gravity.CENTER, 0, 0);
                                toast.show();
                                return;
                            }
                            else
                            {
                                NetworkInfo.State netState = networkInfo
                                        .getState();
                                if (netState != NetworkInfo.State.CONNECTED)
                                {
                                    dbgUtil.Logd(
                                            "Current Network info",
                                            "not Connected!State="
                                                    + netState);
//                                    canstart = false;

                                    Toast toast = Toast.makeText(getApplicationContext(),
                                            "App network connection. Please try upload manually later.",
                                            Toast.LENGTH_LONG);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                    return;
                                }
                                else
                                {
                                    int iconntype = -1;
                                    iconntype = networkInfo
                                            .getType();

                                    SharedPreferences pref = RedAntApplication
                                            .getInstance()
                                            .getSharedPreferences(
                                                    "UploadManager",
                                                    0);
                                    boolean
                                            wifi_only
                                            =pref.getBoolean("wifi_only",
                                            false);
                                    if(wifi_only == true
                                            && iconntype !=
                                            ConnectivityManager.TYPE_WIFI
                                            && iconntype !=
                                            9/* earthnet */)
                                    {
//                                    canstart = false;

                                        Toast toast = Toast.makeText(getApplicationContext(),
                                                "App is set to upload via WIFI only. Please change your setting or try upload manually later.",
                                                Toast.LENGTH_LONG);
                                        toast.setGravity(Gravity.CENTER, 0, 0);
                                        toast.show();
                                        return;
                                    }
                                }

                            }
//                            if(!canstart)
//                            {
//                                Toast toast = Toast.makeText(getApplicationContext(),
//                                        "App is set to upload via WIFI only. Please change your setting or try upload manually later.",
//                                        Toast.LENGTH_LONG);
//                                toast.setGravity(Gravity.CENTER, 0, 0);
//                                toast.show();
//                                return;
//                            }

                            v.setVisibility(View.GONE);
                            uploadManager.startTask(task);

                        }
                    });
                }



            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+" file   " + item.getString("file","no file"));
            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;
        }
    }
}
