package com.maxmoney.maxcddconsole.Activity;

import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

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.github.chrisbanes.photoview.PhotoView;
import com.maxmoney.maxcddconsole.Common.StandardProgressDialog;
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.io.UnsupportedEncodingException;
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 UserSearchActivity extends AppCompatActivity {

    LinearLayout linear_user_details;
    TextView textView_customerType,textView_pid,textView_status;
    EditText editText_fullName,editText_email,editText_idType,editText_idNo,editText_dob,editText_address,
            editText_city,editText_country,editText_nationality,editText_mobile,editText_state,editText_postalCode,
            editText_companyName,editText_companyType,editText_incomeSource,editText_natureSource,editText_createTime,
            editText_createBy,editText_validateAt,editText_validateBy,editText_complienceAt,editText_complienceBy,editText_search;
    ImageView image_front,image_back;
    ImageView imageView_back;
    Button button_sms,button_search;
    StandardProgressDialog standardProgressDialog;
    String session,imageBack,imageFront;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_search);

        session = getIntent().getStringExtra("session");
        standardProgressDialog = new StandardProgressDialog(this.getWindow().getContext());
        linear_user_details = findViewById(R.id.linear_user_details);

        textView_customerType = findViewById(R.id.textView_customerType);
        textView_pid = findViewById(R.id.textView_pid);
        textView_status = findViewById(R.id.textView_status);

        editText_fullName = findViewById(R.id.editText_fullName);
        editText_fullName.setFocusable(false);
        editText_email = findViewById(R.id.editText_email);
        editText_email.setFocusable(false);
        editText_idType = findViewById(R.id.editText_idType);
        editText_idType.setFocusable(false);
        editText_idNo = findViewById(R.id.editText_idNo);
        editText_idType.setFocusable(false);
        editText_dob = findViewById(R.id.editText_dob);
        editText_dob.setFocusable(false);
        editText_address = findViewById(R.id.editText_address);
        editText_address.setFocusable(false);
        editText_city = findViewById(R.id.editText_city);
        editText_city.setFocusable(false);
        editText_country = findViewById(R.id.editText_country);
        editText_country.setFocusable(false);
        editText_nationality = findViewById(R.id.editText_nationality);
        editText_nationality.setFocusable(false);
        editText_mobile = findViewById(R.id.editText_mobile);
        editText_mobile.setFocusable(false);
        editText_state = findViewById(R.id.editText_state);
        editText_state.setFocusable(false);
        editText_postalCode = findViewById(R.id.editText_postalCode);
        editText_postalCode.setFocusable(false);
        editText_companyName = findViewById(R.id.editText_companyName);
        editText_companyName.setFocusable(false);
        editText_companyType = findViewById(R.id.editText_companyType);
        editText_companyType.setFocusable(false);
        editText_incomeSource = findViewById(R.id.editText_incomeSource);
        editText_incomeSource.setFocusable(false);
        editText_natureSource = findViewById(R.id.editText_natureSource);
        editText_natureSource.setFocusable(false);
        editText_createTime = findViewById(R.id.editText_createTime);
        editText_createTime.setFocusable(false);
        editText_createBy = findViewById(R.id.editText_createBy);
        editText_createBy.setFocusable(false);
        editText_validateAt = findViewById(R.id.editText_validateAt);
        editText_validateAt.setFocusable(false);
        editText_validateBy = findViewById(R.id.editText_validateBy);
        editText_validateBy.setFocusable(false);
        editText_complienceAt = findViewById(R.id.editText_complienceAt);
        editText_complienceAt.setFocusable(false);
        editText_complienceBy = findViewById(R.id.editText_complienceBy);
        editText_complienceBy.setFocusable(false);

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

        button_search = findViewById(R.id.button_search);
        editText_search = findViewById(R.id.editText_search);
        button_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(editText_search.getText().toString().equals("")){
                    editText_search.setError("Please enter id");
                }else{
                    standardProgressDialog.show();
                    userSearch();
                }
            }
        });

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

        image_front.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(UserSearchActivity.this);
                View mView = getLayoutInflater().inflate(R.layout.dialog_custom_layout, null);
                PhotoView photoView = mView.findViewById(R.id.imageView);
                Picasso.get().load(imageFront).into(photoView);
                mBuilder.setView(mView);
                AlertDialog mDialog = mBuilder.create();
                mDialog.show();
            }
        });

        image_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(UserSearchActivity.this);
                View mView = getLayoutInflater().inflate(R.layout.dialog_custom_layout, null);
                PhotoView photoView = mView.findViewById(R.id.imageView);
                Picasso.get().load(imageBack).into(photoView);
                mBuilder.setView(mView);
                AlertDialog mDialog = mBuilder.create();
                mDialog.show();
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

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

        linear_user_details.setVisibility(View.GONE);
    }

    private void userSearch() {
        StringRequest stringRequest = new StringRequest(GET, BasedUrl.URL_STAGING +"users/identification-document/"+editText_search.getText().toString(),
                new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        standardProgressDialog.dismiss();
                        linear_user_details.setVisibility(View.VISIBLE);
                        try {
                            JSONObject object = new JSONObject(response);

                            textView_customerType.setText("Customer Type : "+object.getString("customerType"));
                            textView_pid.setText("PID : "+object.getString("idNo"));
                            textView_status.setText("Status : "+object.getString("status"));

                            editText_fullName.setText(object.getString("fullName"));
                            editText_email.setText(object.getString("email"));
                            editText_idType.setText(object.getString("idType"));
                            editText_idNo.setText(object.getString("idNo"));
                            editText_dob.setText(createDate(Long.parseLong(object.getString("dob"))));

                            editText_mobile.setText(object.getString("mobile"));
                            editText_companyName.setText(object.getString("companyName"));
                            editText_companyType.setText(object.getString("companyType"));

                            editText_createTime.setText(createDate(Long.parseLong(object.getString("created"))));
                            editText_createBy.setText(object.getString("createdBy"));
                            editText_validateAt.setText(createDate(Long.parseLong(object.getString("validatedAt"))));
                            editText_validateBy.setText(object.getString("validatedBy"));

                            editText_complienceAt.setText(object.getString("complicateDoneAt"));
                            editText_complienceBy.setText(object.getString("complianceDoneBy"));


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

                            JSONObject riskProfile = new JSONObject(object.getString("riskProfile"));
                            JSONObject cddOBJ = new JSONObject(riskProfile.getString("cdd"));
                            editText_address.setText(cddOBJ.getString("address"));
                            editText_city.setText(cddOBJ.getString("city"));
                            editText_country.setText(cddOBJ.getString("country"));
                            editText_nationality.setText(cddOBJ.getString("nationality"));
                            editText_state.setText(cddOBJ.getString("state"));
                            editText_postalCode.setText(cddOBJ.getString("postalCode"));

                            JSONObject eddOBJ = new JSONObject(riskProfile.getString("edd"));
                            editText_incomeSource.setText(eddOBJ.getString("incomeSource"));
                            editText_natureSource.setText(eddOBJ.getString("natureOfBusiness"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        standardProgressDialog.dismiss();
                        parseVolleyError(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 parseVolleyError(VolleyError error) {
        linear_user_details.setVisibility(View.GONE);
        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) {
        }
    }

    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);
    }

}
