package com.maxmoney.maxcddconsole.Activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.jsibbold.zoomage.ZoomageView;
import com.maxmoney.maxcddconsole.Connectivity.BasedUrl;
import com.maxmoney.maxcddconsole.R;
import com.squareup.picasso.Picasso;

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

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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

public class ApproveCustomerClickActivity extends AppCompatActivity {

    String session = "",email ="";
    TextView textView_fullname,textView_status,textView_email,textView_dob,textView_idtype,textView_idNo,textView_nationality,textView_country,
            textView_address,textView_mobile,textView_state,textView_city,textView_pep,textView_ofa;
    ZoomageView image_back,image_front;
    Button button_approve,button_edit,button_reject;
    ScrollView main;
    VideoView videoView;

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

        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        session = getIntent().getStringExtra("session");
        email = getIntent().getStringExtra("email");

        textView_fullname = findViewById(R.id.textView_fullname);
        textView_status = findViewById(R.id.textView_status);
        textView_email = findViewById(R.id.textView_email);
        textView_dob = findViewById(R.id.textView_dob);
        textView_idtype = findViewById(R.id.textView_idtype);
        textView_idNo = findViewById(R.id.textView_idNo);
        textView_nationality = findViewById(R.id.textView_nationality);
        textView_country = findViewById(R.id.textView_country);
        textView_address = findViewById(R.id.textView_address);
        textView_mobile = findViewById(R.id.textView_mobile);
        textView_state = findViewById(R.id.textView_state);
        textView_city = findViewById(R.id.textView_city);
        textView_pep = findViewById(R.id.textView_pep);
        textView_ofa = findViewById(R.id.textView_ofa);

        image_back = findViewById(R.id.image_back);
        image_front = findViewById(R.id.image_front);

        button_approve = findViewById(R.id.button_approve);
        button_edit = findViewById(R.id.button_edit);
        button_reject = findViewById(R.id.button_reject);
        videoView = findViewById(R.id.videoView);

        main = (ScrollView) findViewById(R.id.dealscroll);

        getUserDetails();

        button_reject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogReject();
            }
        });

        button_approve.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogApprove();
            }
        });
    }

    public void getUserDetails(){
        StringRequest stringRequest = new StringRequest(GET, BasedUrl.URL_STAGING +"users/"+email,
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject obj = new JSONObject(response);

                            textView_fullname.setText(obj.getString("name"));
                            textView_status.setText(obj.getString("status"));
                            textView_email.setText(obj.getString("email"));
                            if(obj.getString("dob").equals("null")){
                                textView_dob.setText("");
                            }else{
                                textView_dob.setText(createDate(Long.parseLong(obj.getString("dob"))));
                            }

                            textView_idtype.setText(obj.getString("idType"));
                            textView_idNo.setText(obj.getString("idNo"));
                            textView_mobile.setText(obj.getString("mobile"));

                            if(obj.has("riskProfile")){
                                JSONObject risk = new JSONObject(obj.getString("riskProfile"));
                                if(risk.has("cdd")){
                                    JSONObject cdd = new JSONObject(risk.getString("cdd"));
                                    textView_nationality.setText(cdd.getString("nationality"));
                                    textView_country.setText(cdd.getString("nationalityCountry"));
                                    textView_address.setText(cdd.getString("address"));
                                    textView_state.setText(cdd.getString("state"));
                                    textView_city.setText(cdd.getString("city"));
                                }
                            }


                            if(obj.has("images")){
                                JSONObject img = new JSONObject(obj.getString("images"));
                                if(obj.getString("idType").equals("Passport")){
                                    String imageBack = BasedUrl.URL_STAGING+"customers/"+obj.getString("idNo")+"/images/"+img.getString("Back")+"?api-key="+session;
                                    String imageFront = BasedUrl.URL_STAGING+"customers/"+obj.getString("idNo")+"/images/"+img.getString("Front")+"?api-key="+session;
                                    Picasso.get().load(imageBack).into(image_back);
                                    Picasso.get().load(imageFront).into(image_front);
                                }else{
                                    String imageBack = BasedUrl.URL_STAGING+"customers/"+obj.getString("idNo")+"/images/"+img.getString("Back")+"?api-key="+session;
                                    String imageFront = BasedUrl.URL_STAGING+"customers/"+obj.getString("idNo")+"/images/"+img.getString("Front")+"?api-key="+session;
                                    Picasso.get().load(imageBack).into(image_back);
                                    Picasso.get().load(imageFront).into(image_front);
                                }
                            }

                            checkPEP();
                            checkOfa();

                            videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                @Override
                                public void onPrepared(MediaPlayer mp) {
                                    MediaController mediaController = new MediaController(ApproveCustomerClickActivity.this);
                                    videoView.setMediaController(mediaController);
                                    mediaController.setAnchorView(videoView);
                                }
                            });
                            videoView.setVideoURI(Uri.parse("https://www.maxmoney.com/my/app/android/video/"+textView_idNo.getText().toString()+".mp4"));

                            videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                @Override
                                public void onCompletion(MediaPlayer mediaPlayer) {
                                }
                            });

                            videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                                @Override
                                public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                                    return false;
                                }
                            });

                            main.post(new Runnable() {
                                public void run() {
                                    main.scrollTo(0,0);
                                }
                            });

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();

                return params;
            }

            @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 checkPEP() {
        StringRequest stringRequest = new StringRequest(GET, BasedUrl.URL_STAGING +"risks/peps/"+textView_fullname.getText().toString()+"?country="+textView_country.getText().toString(),
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject check = new JSONObject(response);
                            if(check.getString("total").equals("0")){
                                textView_pep.setText("NO");
                            }else{
                                textView_pep.setText("YES");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                return params;
            }
            @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 checkOfa(){
        StringRequest stringRequest = new StringRequest(GET, BasedUrl.URL_STAGING +"risks/ofac/"+textView_fullname.getText().toString(),
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject check = new JSONObject(response);
                            if(check.getString("total").equals("0")){
                                textView_ofa.setText("NO");
                            }else{
                                textView_ofa.setText("YES");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                return params;
            }
            @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 CharSequence createDate(long timestamp) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(timestamp);
        Date d = c.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        return sdf.format(d);
    }

    public void dialogReject(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("Are you sure want to reject this?");

        alertDialogBuilder.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        rejectUser();
                    }
                });

        alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        alertDialogBuilder.setCancelable(false);
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    public void dialogApprove(){
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("Are you sure want to Approve this?");

        alertDialogBuilder.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        approveUser();
                    }
                });

        alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        alertDialogBuilder.setCancelable(false);
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    public void rejectUser(){
        StringRequest stringRequest = new StringRequest(PUT, BasedUrl.URL_STAGING +"users/"+textView_email.getText().toString(),
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(getApplicationContext(),"User Removed",Toast.LENGTH_SHORT).show();
                        Intent next = new Intent(getApplicationContext(),ApproveActivity.class);
                        next.putExtra("session",session);
                        startActivity(next);
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("status","removed");
                params.put("requestSource","agent");
                return params;
            }
            @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 approveUser(){
        StringRequest stringRequest = new StringRequest(PUT, BasedUrl.URL_STAGING +"users/"+textView_email.getText().toString(),
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(getApplicationContext(),"User Approve",Toast.LENGTH_SHORT).show();
                        Intent next = new Intent(getApplicationContext(),ApproveActivity.class);
                        next.putExtra("session",session);
                        startActivity(next);
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("status","active");
                params.put("requestSource","agent");
                return params;
            }
            @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);
    }
}
