package com.maxmoney.maxcddconsole.Activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.maxmoney.maxcddconsole.Adapter.ApproveUserAdapter;
import com.maxmoney.maxcddconsole.Common.StandardProgressDialog;
import com.maxmoney.maxcddconsole.Connectivity.BasedUrl;
import com.maxmoney.maxcddconsole.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static com.android.volley.Request.Method.GET;

public class ApproveActivity extends AppCompatActivity implements View.OnClickListener,AbsListView.OnScrollListener{

    EditText editText_email;
    public static String session;
    StandardProgressDialog standardProgressDialog;
    ImageView imageView_back,imageView_refresh;
    ListView list_view;
    private ApproveUserAdapter mPLAdapter;
    private ArrayList<Map<String, String>> data = null;
    private int currentPagination = 1;
    private int total = 100;
    private int pageClick = 0;
    Button button_search;

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

        standardProgressDialog = new StandardProgressDialog(this.getWindow().getContext());
        session = getIntent().getStringExtra("session");

        imageView_back = findViewById(R.id.imageView_back);
        list_view = findViewById(R.id.list_view);
        imageView_refresh = findViewById(R.id.imageView_refresh);

        imageView_back.setOnClickListener(this);
        imageView_refresh.setOnClickListener(this);

        getTotal();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onBackPressed() {
        Intent next = new Intent(getApplicationContext(), DashboardActivity.class);
        next.putExtra("session",session);
        startActivity(next);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageView_back : {
               onBackPressed();
                break;
            }
            case R.id.imageView_refresh : {
                currentPagination = 1;
                getTotal();
                break;
            }
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (totalItemCount >0 && list_view != null) {
            int lastPosition = list_view.getLastVisiblePosition();
            if (lastPosition + 1 == totalItemCount && data.size() < total) {
                currentPagination++;
                getListUser();
            }
        }
    }

    public void getTotal(){
        data = new ArrayList<Map<String, String>>(); // data
        mPLAdapter = new ApproveUserAdapter(getApplicationContext(), data);
        list_view.setAdapter(mPLAdapter);
        list_view.setOnScrollListener(this);


        StringRequest stringRequest = new StringRequest(GET, BasedUrl.URL_STAGING +"users?status=inactive&page="+currentPagination,
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {

                            JSONObject obj1 = new JSONObject(response);
                            total = Integer.parseInt(obj1.getString("total"));
                            Log.d("total data omoe", String.valueOf(total));
                            getListUser();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "Please check Internet Connection !!", Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap();
                headers.put("api-key",session);
                return headers;
            }
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("status","inactive");
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);
    }

    public void getListUser(){
        StringRequest stringRequest = new StringRequest(GET, BasedUrl.URL_STAGING +"users?status=inactive&page="+currentPagination,
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {

                            JSONObject obj1 = new JSONObject(response);
                            JSONArray array = obj1.getJSONArray("users");
                            for(int i = 0; i< array.length(); i++){
                                JSONObject product = array.getJSONObject(i);
                                Map<String, String> addData = new HashMap<String, String>();
                                addData.put("msg1", product.getString("idNo"));
                                addData.put("msg2", product.getString("email"));
                                addData.put("msg3", product.getString("name"));
                                data.add(addData);
                            }
                            mPLAdapter.refreshData(data);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(getApplicationContext(), "Please check Internet Connection !!", Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap();
                headers.put("api-key",session);
                return headers;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);
    }

    public void searchByEmail(){
        data = new ArrayList<Map<String, String>>(); // data
        mPLAdapter = new ApproveUserAdapter(getApplicationContext(), data);
        list_view.setAdapter(mPLAdapter);
        StringRequest stringRequest = new StringRequest(GET, BasedUrl.URL_STAGING +"users/"+editText_email.getText().toString(),
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject obj1 = new JSONObject(response);

                            if(obj1.getString("status").equals("inactive")){
                                Map<String, String> addData = new HashMap<String, String>();
                                addData.put("msg1", obj1.getString("idNo"));
                                addData.put("msg2", obj1.getString("email"));
                                addData.put("msg3", obj1.getString("name"));
                                data.add(addData);
                            }else {
                                Toast.makeText(getApplicationContext(),"This ID already active",Toast.LENGTH_SHORT).show();
                            }

                            mPLAdapter.refreshData(data);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        parseVolleyError(error);
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap();
                headers.put("api-key",session);
                return headers;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);
    }

    public void parseVolleyError(VolleyError error) {
        try {
            String responseBody = new String(error.networkResponse.data, "utf-8");
            JSONObject data = new JSONObject(responseBody);
            if(data.has("message")){
                Toast.makeText(getApplicationContext(), data.getString("message"),Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(getApplicationContext(),"Login error",Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
        } catch (UnsupportedEncodingException errorr) {
        }
    }

}
