package com.maxmoney.maxcddconsole.Activity;

import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.maxmoney.maxcddconsole.Common.StandardProgressDialog;
import com.maxmoney.maxcddconsole.R;

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

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class CddActivity extends AppCompatActivity {
    String token,idType = "",idNo = "",email = "",customerName = "";
    StandardProgressDialog standardProgressDialog;

    TextView textView_name,textView_idNo;
    Spinner spinner_business,spinner_sourceIncome;

    ImageView imageView_front_ic,imageView_back_ic,imageView_front_passport,imageView_back_passport,imageView_back;
    LinearLayout linear_passport,linear_ic;
    Button button_next;
    Uri file_front,file_back;
    private static final int CAMERA_FRONT = 1;
    private static final int CAMERA_BACK = 2;
    String front_doc = "",back_doc ="";

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

        standardProgressDialog = new StandardProgressDialog(this.getWindow().getContext());

        token = getIntent().getStringExtra("session");
        idType = getIntent().getStringExtra("idType");
        idNo = getIntent().getStringExtra("idNo");
        email = getIntent().getStringExtra("email");
        customerName = getIntent().getStringExtra("customerName");

        textView_name = findViewById(R.id.textView_name);
        textView_idNo = findViewById(R.id.textView_idNo);

        spinner_business = findViewById(R.id.spinner_business);
        spinner_sourceIncome = findViewById(R.id.spinner_sourceIncome);

        imageView_front_ic = findViewById(R.id.imageView_front_ic);
        imageView_back_ic = findViewById(R.id.imageView_back_ic);
        imageView_front_passport = findViewById(R.id.imageView_front_passport);
        imageView_back_passport = findViewById(R.id.imageView_back_passport);
        imageView_back = findViewById(R.id.imageView_back);

        linear_passport = findViewById(R.id.linear_passport);
        linear_ic = findViewById(R.id.linear_ic);
        button_next = findViewById(R.id.button_next);

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

        if(idType.equals("Passport")){
            linear_passport.setVisibility(View.VISIBLE);
            linear_ic.setVisibility(View.GONE);

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

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

        }else{
            linear_passport.setVisibility(View.GONE);
            linear_ic.setVisibility(View.VISIBLE);

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

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

        button_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(spinner_business.getSelectedItem().toString().equals("Please choose nature of business")){
                    Toast.makeText(getApplicationContext(),"Please choose nature of business",Toast.LENGTH_SHORT).show();
                }else if(spinner_sourceIncome.getSelectedItem().toString().equals("Please choose source of income")){
                    Toast.makeText(getApplicationContext(),"Please choose source of income",Toast.LENGTH_SHORT).show();
                }else if(front_doc.equals("")){
                    Toast.makeText(getApplicationContext(),"Please upload front document",Toast.LENGTH_SHORT).show();
                }else if(back_doc.equals("")){
                    Toast.makeText(getApplicationContext(),"Please upload back document",Toast.LENGTH_SHORT).show();
                }else{
                    standardProgressDialog.show();
                    RegisterCdd();
                }
            }
        });
    }

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

        textView_name.setText(customerName);
        textView_idNo.setText(idNo);

    }

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

    public void frontCamera() {
        ContentValues values = new ContentValues(1);
        values.put(MediaStore.Images.Media.MIME_TYPE, "documentFront.jpg");
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        file_front =  getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, file_front);
        startActivityForResult(intent, CAMERA_FRONT);
    }

    public void backCamera() {
        ContentValues values = new ContentValues(1);
        values.put(MediaStore.Images.Media.MIME_TYPE, "documentBack.jpg");
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        file_back =  getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, file_back);
        startActivityForResult(intent, CAMERA_BACK);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (resultCode == RESULT_OK) {
                if(requestCode == CAMERA_FRONT){
                    Uri uri = file_front;
                    try {
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                        front_doc = getStringImage(bitmap);
                        Log.d("bitmap", String.valueOf(bitmap));
                        if(idType.equals("Passport")){
                           imageView_front_passport.setImageBitmap(bitmap);
                        }else{
                          imageView_front_ic.setImageBitmap(bitmap);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(requestCode == CAMERA_BACK){
                    Uri uri = file_back;
                    try {
                        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                        back_doc = getStringImage(bitmap);
                        if(idType.equals("Passport")){
                            imageView_back_passport.setImageBitmap(bitmap);
                        }else{
                            imageView_back_ic.setImageBitmap(bitmap);
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    }

    public String getStringImage(Bitmap bmp) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 30, baos);
        byte[] imageBytes = baos.toByteArray();
        final String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return imageString;
    }

    public void RegisterCdd(){
        String URLs = "https://www.maxmoney.com/cdd-app/process/register_max_cdd_apps.php";
        final StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        standardProgressDialog.dismiss();
                        try {
                            JSONObject obj = new JSONObject(response);
                            if (obj.getString("status").equals("false")) {
                                if(obj.getString("message").equals("Authentication failed")){
                                    standardProgressDialog.dismiss();
                                    Toast.makeText(getApplicationContext(), obj.getString("message") + "Please Try Again", Toast.LENGTH_LONG).show();
                                }else{
                                    standardProgressDialog.dismiss();
                                    Toast.makeText(getApplicationContext(), obj.getString("message") + "Please Try Again", Toast.LENGTH_LONG).show();
                                }
                            }else{
                                standardProgressDialog.dismiss();
                                Toast.makeText(getApplicationContext(), "Cdd successful", Toast.LENGTH_LONG).show();

                                Intent next = new Intent(getApplicationContext(),DashboardActivity.class);
                                next.putExtra("session",token);
                                startActivity(next);
                            }
                        } catch (JSONException e) {
                            standardProgressDialog.dismiss();
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        standardProgressDialog.dismiss();
                    }
                }) {
            @Override
            protected Map<String, String> getParams ()  throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("token",token+"");
                params.put("idNo", idNo);
                params.put("natureOfBusiness",spinner_business.getSelectedItem().toString());
                params.put("incomeSource",spinner_sourceIncome.getSelectedItem().toString());
                params.put("email", email);
                params.put("idType", idType);
                params.put("front", front_doc+"");
                params.put("back",back_doc+"");
                return params;
            }

        };
        int socketTimeout = 30000;
        RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        stringRequest.setRetryPolicy(policy);
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }
}
