package com.example.instilostandfound;
import com.example.instilostandfound.R;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
import com.google.firebase.storage.UploadTask;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.icu.text.SimpleDateFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.FirebaseAuth;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.FileProvider;

import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.util.Date;
import java.util.Random;
//import static android.app.Activity.RESULT_OK;
//import com.squareup.picasso.Picasso;

public class FoundItem extends AppCompatActivity implements View.OnClickListener{
    //private FirebaseAuth mAuth;
    EditText title;
    EditText place;
    EditText desc;
    EditText date;
    Spinner category;
    String username;
    ImageView camera;
    String[] items = new String[]{"Others","Electronic", "2", "three"};
    private static final int CAMERA_REQUEST = 1888;
    private ImageView imageView;
    private static final int MY_CAMERA_PERMISSION_CODE = 100;
    private DatabaseReference mDatabase;
    public Uri mImageUri;
    public Uri uploadSessionUri;
    int PICK_IMAGE_REQUEST = 111;
    ProgressDialog pd;
    private StorageTask mUploadTask;


// ...
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("FoundData");
    StorageReference mStorage  = FirebaseStorage.getInstance().getReference("Images");


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_found_item);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        username = getIntent().getStringExtra("username");
        title = findViewById(R.id.title);
        place = findViewById(R.id.place);
        desc = findViewById(R.id.desc);
        date = findViewById(R.id.date);
        category = findViewById(R.id.category);
        camera = findViewById(R.id.camera);
        camera.setOnClickListener(this);
        pd = new ProgressDialog(this);
        pd.setMessage("Uploading....");



        findViewById(R.id.submit).setOnClickListener(this);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
        category.setAdapter(adapter);

    }

    private void SubmitFound() {
        final String Title = title.getText().toString().trim();
        final String Place = place.getText().toString().trim();
        final String Desc = desc.getText().toString().trim();
        final String Date = date.getText().toString().trim();

        if (title.getText().toString().trim().isEmpty()) {
            title.setError("Please enter title");
            title.requestFocus();
            return;
        }

        if (place.toString().trim().isEmpty()) {
            place.setError("Please enter location");
            place.requestFocus();
            return;
        }
        if (mImageUri != null) {
            pd.show();
            final StorageReference fileReference = mStorage.child(System.currentTimeMillis()
                    + "." + getExtension(mImageUri));
            mUploadTask = fileReference.putFile(mImageUri)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {

                                }
                            }, 500);

                            mImageUri = null;
                            Toast.makeText(FoundItem.this, "Upload successful", Toast.LENGTH_LONG).show();

                            taskSnapshot.getMetadata().getReference().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    uploadSessionUri = uri;

                                    Date datef = new Date();
                                    CreateFoundObject upload = new CreateFoundObject(username,Title ,uri.toString(),"location", Desc,
                                            "category", datef);
                                    String uploadId = myRef.push().getKey();
                                    Log.v("UploadID", uploadId);
                                    myRef.child(uploadId).setValue(upload);
                                    title.setText("");
                                    place.setText("");
                                    desc.setText("");
                                    date.setText("");
                                    pd.dismiss();
                                    Toast.makeText(FoundItem.this,"SUBMIT SUCCESSFUL",Toast.LENGTH_LONG).show();


                                }
                            })
                                    .addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull Exception e) {
                                            Toast.makeText(FoundItem.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                                        }
                                    });


                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(FoundItem.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });

        } else {
            Date datef = new Date();
            Toast.makeText(FoundItem.this, "No file selected", Toast.LENGTH_SHORT).show();
            CreateFoundObject upload = new CreateFoundObject(username,Title ,"NO-IMAGE","location", Desc,
                    "category", datef);
            String uploadId = myRef.push().getKey();
            Log.v("UploadID", uploadId);
            myRef.child(uploadId).setValue(upload);
            title.setText("");
            place.setText("");
            desc.setText("");
            date.setText("");
            Toast.makeText(FoundItem.this,"SUBMIT SUCCESSFUL -NO IMAGE UPLOADED!",Toast.LENGTH_LONG).show();

        }


       // String uploadurl = uploadSessionUri.toString();
       // Log.v("Upload url",uploadurl);
/*        createDemo upload = new createDemo(username,
                Title, Desc, Place, Date);
        String uploadId = myRef.push().getKey();
        Log.v("UploadID", uploadId);
        myRef.child(uploadId).setValue(upload);
        title.setText("");
        place.setText("");
        desc.setText("");

        Toast.makeText(FoundItem.this,"SUBMIT SUCCESSFUL",Toast.LENGTH_LONG).show();*/

    }
    private  String getExtension(Uri uri)
    {
        ContentResolver cr = getContentResolver();
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        return  mimeTypeMap.getExtensionFromMimeType(cr.getType(uri));
    }





    @RequiresApi(api = Build.VERSION_CODES.N)
    public void onClick(View view)
    {
        switch (view.getId())
        {
            case R.id.submit:
                SubmitFound();
                break;
            case R.id.camera:
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_PICK);
                startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            mImageUri = data.getData();

            try {
                //getting image from gallery
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), mImageUri);

                //Setting image to ImageView
                camera.setImageBitmap(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
