package com.renitha.Activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.media.ThumbnailUtils;
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.google.gson.JsonObject;
import com.renitha.Interface.APIService;
import com.renitha.Model.APIUrl;
import com.renitha.Pref.Pref;
import com.renitha.R;
import com.renitha.Volley.AppHelper;
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.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class UploadPhotoActivity1 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;
    CardView card2;
    CardView card3;
    CardView card4;
    CardView card5;
    CardView card6;
    CardView card7;
    CardView card8;
    CardView card9;
    CardView card10;

    ImageView image1;
    ImageView image2;
    ImageView image3;
    ImageView image4;
    ImageView image5;
    ImageView image6;
    ImageView image7;
    ImageView image8;
    ImageView image9;
    ImageView image10;

    TextView textView1;
    TextView textView2;
    TextView textView3;
    TextView textView4;
    TextView textView5;
    TextView textView6;
    TextView textView7;
    TextView textView8;
    TextView textView9;
    TextView textView10;

    int frame;
    Button btnAdd;

    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);
        image2 = (ImageView)findViewById(R.id.image2);
        image3 = (ImageView)findViewById(R.id.image3);
        image4 = (ImageView)findViewById(R.id.image4);
        image5 = (ImageView)findViewById(R.id.image5);
        image6 = (ImageView)findViewById(R.id.image6);
        image7 = (ImageView)findViewById(R.id.image7);
        image8 = (ImageView)findViewById(R.id.image8);
        image9 = (ImageView)findViewById(R.id.image9);
        image10 = (ImageView)findViewById(R.id.image10);

        card1 = findViewById(R.id.card1);
        card2 = findViewById(R.id.card2);
        card3 = findViewById(R.id.card3);
        card4 = findViewById(R.id.card4);
        card5 = findViewById(R.id.card5);
        card6 = findViewById(R.id.card6);
        card7 = findViewById(R.id.card7);
        card8 = findViewById(R.id.card8);
        card9 = findViewById(R.id.card9);
        card10 = findViewById(R.id.card10);

        card1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

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

        card2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                frame = 2;
                openGallery();
            }
        });

        card3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                frame = 3;
                openGallery();
            }
        });

        card4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                frame = 4;
                openGallery();
            }
        });

        card5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                frame = 5;
                openGallery();
            }
        });

        card6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                frame = 6;
                openGallery();
            }
        });
        card7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                frame = 7;
                openGallery();
            }
        });
        card8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                frame = 8;
                openGallery();
            }
        });
        card9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                frame = 9;
                openGallery();
            }
        });
        card10.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                frame = 10;
                openGallery();
            }
        });
        textView1 =  findViewById(R.id.textView1);
        textView2 =  findViewById(R.id.textView2);
        textView3 =  findViewById(R.id.textView3);
        textView4 =  findViewById(R.id.textView4);
        textView5 =  findViewById(R.id.textView5);
        textView6 =  findViewById(R.id.textView6);
        textView7 =  findViewById(R.id.textView7);
        textView8 =  findViewById(R.id.textView8);
        textView9 =  findViewById(R.id.textView9);
        textView10 =  findViewById(R.id.textView10);

        btnAdd = findViewById(R.id.btnAdd);

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadPhoto();
            }
        });
        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())) {

                progressBar.setVisibility(View.VISIBLE);
                btnAdd.setEnabled(false);

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

                String url = APIUrl.BASE_URL +"api_upload_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("")

                        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(), "Photos Uploaded Successfully", Toast.LENGTH_SHORT).show();

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

                            } else{

                                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) {

                        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"));
                        }
                        if(image2.getDrawable() != null) {
                            params.put("file2", new DataPart("2.jpg", getFileDataFromDrawable(((BitmapDrawable)image2.getDrawable()).getBitmap()), "image/jpeg"));                        //params.put("cover", new DataPart("file_cover.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mCoverImage.getDrawable()), "image/jpeg"));
                        }
                        if(image3.getDrawable() != null) {
                            params.put("file3", new DataPart("3.jpg", getFileDataFromDrawable(((BitmapDrawable)image3.getDrawable()).getBitmap()), "image/jpeg"));                        //params.put("cover", new DataPart("file_cover.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mCoverImage.getDrawable()), "image/jpeg"));
                        }
                        if(image4.getDrawable() != null) {
                            params.put("file4", new DataPart("4.jpg", getFileDataFromDrawable(((BitmapDrawable)image4.getDrawable()).getBitmap()), "image/jpeg"));                        //params.put("cover", new DataPart("file_cover.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mCoverImage.getDrawable()), "image/jpeg"));
                        }
                        if(image5.getDrawable() != null) {
                            params.put("file5", new DataPart("5.jpg", getFileDataFromDrawable(((BitmapDrawable)image5.getDrawable()).getBitmap()), "image/jpeg"));                        //params.put("cover", new DataPart("file_cover.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mCoverImage.getDrawable()), "image/jpeg"));
                        }
                        if(image6.getDrawable() != null) {
                            params.put("file6", new DataPart("6.jpg", getFileDataFromDrawable(((BitmapDrawable)image6.getDrawable()).getBitmap()), "image/jpeg"));                        //params.put("cover", new DataPart("file_cover.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mCoverImage.getDrawable()), "image/jpeg"));
                        }
                        if(image7.getDrawable() != null) {
                            params.put("file7", new DataPart("7.jpg", getFileDataFromDrawable(((BitmapDrawable)image7.getDrawable()).getBitmap()), "image/jpeg"));                        //params.put("cover", new DataPart("file_cover.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mCoverImage.getDrawable()), "image/jpeg"));
                        }
                        if(image8.getDrawable() != null) {
                            params.put("file8", new DataPart("8.jpg", getFileDataFromDrawable(((BitmapDrawable)image8.getDrawable()).getBitmap()), "image/jpeg"));                        //params.put("cover", new DataPart("file_cover.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mCoverImage.getDrawable()), "image/jpeg"));
                        }
                        if(image9.getDrawable() != null) {
                            params.put("file9", new DataPart("9.jpg", getFileDataFromDrawable(((BitmapDrawable)image9.getDrawable()).getBitmap()), "image/jpeg"));                        //params.put("cover", new DataPart("file_cover.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mCoverImage.getDrawable()), "image/jpeg"));
                        }
                        if(image10.getDrawable() != null) {
                            params.put("file10", new DataPart("10.jpg", getFileDataFromDrawable(((BitmapDrawable)image10.getDrawable()).getBitmap()), "image/jpeg"));                        //params.put("cover", new DataPart("file_cover.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mCoverImage.getDrawable()), "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.PNG, 80, byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }

    private boolean valid() {

        if(textView1.getVisibility() != View.GONE) {

            return false;
        }
        return true;
    }

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

                }else if(frame == 2) {

                    image2.setImageBitmap(imageBitmap);
                    textView2.setVisibility(View.GONE);

                }else if(frame == 3) {

                    image3.setImageBitmap(imageBitmap);
                    textView3.setVisibility(View.GONE);

                }else if(frame == 4) {

                    image4.setImageBitmap(imageBitmap);
                    textView4.setVisibility(View.GONE);

                }else if(frame == 5) {

                    image5.setImageBitmap(imageBitmap);
                    textView5.setVisibility(View.GONE);

                }else if(frame == 6) {

                    image6.setImageBitmap(imageBitmap);
                    textView6.setVisibility(View.GONE);

                }else if(frame == 7) {

                    image7.setImageBitmap(imageBitmap);
                    textView7.setVisibility(View.GONE);

                }else if(frame == 8) {

                    image8.setImageBitmap(imageBitmap);
                    textView8.setVisibility(View.GONE);

                }else if(frame == 9) {

                    image9.setImageBitmap(imageBitmap);
                    textView9.setVisibility(View.GONE);

                }else {

                    image10.setImageBitmap(imageBitmap);
                    textView10.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);

                    }else if(frame == 2) {

                        image2.setImageBitmap(imageBitmap);
                        textView2.setVisibility(View.GONE);

                    }else if(frame == 3) {

                        image3.setImageBitmap(imageBitmap);
                        textView3.setVisibility(View.GONE);

                    }else if(frame == 4) {

                        image4.setImageBitmap(imageBitmap);
                        textView4.setVisibility(View.GONE);

                    }else if(frame == 5) {

                        image5.setImageBitmap(imageBitmap);
                        textView5.setVisibility(View.GONE);

                    }else if(frame == 6) {

                        image6.setImageBitmap(imageBitmap);
                        textView6.setVisibility(View.GONE);

                    }else if(frame == 7) {

                        image7.setImageBitmap(imageBitmap);
                        textView7.setVisibility(View.GONE);

                    }else if(frame == 8) {

                        image8.setImageBitmap(imageBitmap);
                        textView8.setVisibility(View.GONE);

                    }else if(frame == 9) {

                        image9.setImageBitmap(imageBitmap);
                        textView9.setVisibility(View.GONE);

                    }
                    else {

                        image10.setImageBitmap(imageBitmap);
                        textView10.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;
    }
    */
    }
}