package com.renitha.Activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.google.android.material.snackbar.Snackbar;
import com.renitha.Model.APIUrl;
import com.renitha.Pref.Pref;
import com.renitha.R;
import com.renitha.Volley.BaseController;
import com.renitha.Volley.VolleyMultipartRequest;
import com.renitha.Volley.VolleySingleton;

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

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

public class UploadPhotoCustomerActivity extends AppCompatActivity {

    int PERMISSION_ALL = 1;
    int PICK_IMAGE_CAMERA = 1;
    int PICK_IMAGE_GALLERY = 2;
    private static String[] PERMISSIONS = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA
    };

    CardView card1;
    ImageView image1;
    TextView textView1;

    int frame;
    Button btnAdd,btnFinish,btnSave;

    //View view;

    //ProgressBar progressBar;

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

     //   view = findViewById(android.R.id.content);

        image1 = (ImageView) findViewById(R.id.image1);
        card1 = findViewById(R.id.card1);
        card1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                frame = 1;
                openGallery();
            }
        });

        textView1 = findViewById(R.id.textView1);
        btnAdd = findViewById(R.id.btnAdd);
        btnFinish = findViewById(R.id.btnFinish);
       // btnSave = findViewById(R.id.btnSave);

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

        btnFinish.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Pref.getInstance(getApplicationContext()).setTICKET_ID("");
                startActivity(new Intent(getApplicationContext(), ViewCustomerComplaints.class));
                overridePendingTransition(R.anim.enter, R.anim.exit);
            }
        });

        //progressBar = (ProgressBar) findViewById(R.id.progressBar);
        if (Build.VERSION.SDK_INT >= 29) {

            if (!hasPermissions(this, PERMISSIONS)) {

                ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);

            }

        }
    }

    private void uploadPhoto() {


        //  if(valid()){

        if(BaseController.isNetworkAvailable(getApplicationContext())) {
            final ProgressDialog progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("Wait...");
            progressDialog.show();
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
       //     progressBar.setVisibility(View.VISIBLE);
            btnAdd.setEnabled(false);

            // Instantiate the RequestQueue.
            RequestQueue queue = Volley.newRequestQueue(getApplicationContext());

            String url = APIUrl.BASE_URL +"api_upload_customer_photos.php";

            VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
                @Override
                public void onResponse(NetworkResponse response) {
                    String resultResponse = new String(response.data);
                    try {
                        JSONObject obj = new JSONObject(new String(response.data));
                        // obj.getString("")
                        progressDialog.dismiss();
                        Log.d("mess",obj.getString("message"));
                        Log.d("error",obj.getString("error"));
                       // progressBar.setVisibility(View.GONE);
                        btnAdd.setEnabled(true);

                        if(resultResponse.contains("successfully")) {

                            Toast.makeText(getApplicationContext(), "Photo Uploaded Successfully", Toast.LENGTH_SHORT).show();

                            Intent target = new Intent(getApplicationContext(), UploadPhotoCustomerActivity.class);
                            startActivity(target);

                        } else{
                            Toast.makeText(getApplicationContext(), "Not Saved", Toast.LENGTH_SHORT).show();

                            /*Snackbar.make(view, "Not Saved", Snackbar.LENGTH_SHORT)
                                    .setAction("Action", null).show();*/
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getApplicationContext(), "Not Saved", Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                 /*   Snackbar.make(view, "Try again", Snackbar.LENGTH_SHORT)
                            .setAction("Action", null).show();*/
                    Log.e("Vally::::::::::", error.toString());

                    //progressBar.setVisibility(View.GONE);
                    btnAdd.setEnabled(true);

                }
            }) {
                @Override
                protected Map<String, String> getParams() {


                    Map<String,String> params = new HashMap<>();
                    params.put("ticket_id", Pref.getInstance(getApplicationContext()).getTICKET_ID());
                    return params;
                }

                @Override
                protected Map<String, DataPart> getByteData() {

                    Map<String, DataPart> params = new HashMap<>();
                    // file name could found file base or direct access from real path
                    // for now just get bitmap data from ImageView
                    if(image1.getDrawable() != null) {
                        params.put("file1", new DataPart("1.jpg", getFileDataFromDrawable(((BitmapDrawable)image1.getDrawable()).getBitmap()), "image/jpeg"));
                    }

                    return params;
                }
            };
            VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);

        }else {

            Toast.makeText(getApplicationContext(), "Network not connected", Toast.LENGTH_SHORT).show();
        }


        /*else {

            Snackbar.make(view, "All photos and video are compulsory", Snackbar.LENGTH_SHORT)
                    .setAction("Action", null).show();
        }*/
    }
    public byte[] getFileDataFromDrawable(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }



    public static boolean hasPermissions(Context context, String... permissions) {
        if (context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

    private void openGallery() {
        try {
            if (ContextCompat.checkSelfPermission(getThis(), Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED) {

                ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);

            }else {

                final CharSequence[] options = {"Take Photo", "Choose From Gallery","Cancel"};
                AlertDialog.Builder builder = new AlertDialog.Builder(getThis());
                builder.setTitle("Select Option");
                builder.setItems(options, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        if (options[item].equals("Take Photo")) {
                            dialog.dismiss();

                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(intent, PICK_IMAGE_CAMERA);

                        } else if (options[item].equals("Choose From Gallery")) {
                            dialog.dismiss();

                            Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            startActivityForResult(pickPhoto, PICK_IMAGE_GALLERY);

                        } else if (options[item].equals("Cancel")) {
                            dialog.dismiss();
                        }
                    }
                });
                builder.show();

            }

        }catch (Exception e) {

            Toast.makeText(this, "Error:"+e.getMessage(), Toast.LENGTH_SHORT).show();
            Log.e("EXCEPTION", ""+e);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if(data!=null) {

            if (requestCode == PICK_IMAGE_CAMERA) {

                Bundle extras = data.getExtras();
                Bitmap imageBitmap = (Bitmap) extras.get("data");

                if(frame == 1) {

                    image1.setImageBitmap(imageBitmap);
                    textView1.setVisibility(View.GONE);

                }
                saveImage(imageBitmap);

            }else if (requestCode == PICK_IMAGE_GALLERY) {

                Uri selectedImage = data.getData();

                try {

                    Bitmap imageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);

                    if(frame == 1) {

                        image1.setImageBitmap(imageBitmap);
                        textView1.setVisibility(View.GONE);

                    }
                    saveImage(imageBitmap);

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

            }
        }

    }

    private void saveImage(Bitmap bitmap) {

        File destination = null;

        try {

            bitmap = Bitmap.createScaledBitmap(bitmap,(int)(bitmap.getWidth()*0.5), (int)(bitmap.getHeight()*0.5), true);

            String directory = getThis().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+File.separator+"pictures"+File.separator;

            File f = new File(directory);

            if(!f.exists()) {

                f.mkdir();
            }

            String destinationPath = directory+"t"+frame+".jpg";
            destination = new File(destinationPath);

            FileOutputStream outStream = null;

            outStream = new FileOutputStream(destination);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            outStream.flush();
            outStream.close();

            //Toast.makeText(getThis(),  "Image sample.jpg Saved: ", Toast.LENGTH_LONG).show();

            // Fix
            destination.setExecutable(true);
            destination.setReadable(true);
            destination.setWritable(true);

            MediaScannerConnection.scanFile(getThis(), new String[] {destination.toString()}, null, null);

        }catch(Exception e) {
            Log.e("%%%%%%%%5", ""+e);
            Toast.makeText(getApplicationContext(),  "Error: "+e, Toast.LENGTH_LONG).show();
        }
    }


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

    private Activity getThis() {

        return this;
    }

}
