package com.dreamteam.timelapse

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.Intent.createChooser
import android.graphics.Bitmap
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.core.content.ContextCompat.startActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.SimpleTarget
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import com.bumptech.glide.request.transition.Transition
import java.io.OutputStream


class ImageAdapter(private val imageUrls: List<String>) : RecyclerView.Adapter<ImageAdapter.ImageViewHolder>() {

    // ViewHolder qui contient l'ImageView
    class ImageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val imageView: ImageView = itemView.findViewById(R.id.imageView)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_image, parent, false)
        return ImageViewHolder(view)
    }

    override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {
        val imageUrl = imageUrls[position]
        //Log.e("ImageAdapter", imageUrl)
        Glide.with(holder.itemView.context)
            .load(imageUrl)  // Charge l'image via Glide
            .into(holder.imageView)  // Affiche l'image dans l'ImageView
        holder.itemView.setOnClickListener { view ->
            downloadImage(imageUrl, holder.itemView.context)
        }
    }
    private fun downloadImage(url: String, context: Context) {
        Toast.makeText(context, "Downloading...", Toast.LENGTH_SHORT).show()

        Glide.with(context)
            .asBitmap()
            .load(url)
            .into(object : SimpleTarget<Bitmap>() {
                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                    // Save the image to the Downloads folder using MediaStore
                    val contentValues = ContentValues().apply {
                        put(MediaStore.Images.Media.DISPLAY_NAME, "downloaded_image.jpg") // File name
                        put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
                        put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/") // Save to the Downloads folder
                    }

                    // Insert the image into MediaStore
                    val uri = context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)

                    uri?.let { imageUri ->
                        try {
                            // Open an output stream to write the image to the Downloads folder
                            val outputStream: OutputStream? = context.contentResolver.openOutputStream(imageUri)
                            outputStream?.use {
                                resource.compress(Bitmap.CompressFormat.JPEG, 100, it) // Save the image as JPEG
                                Toast.makeText(context, "Image downloaded successfully", Toast.LENGTH_SHORT).show()
                                val intent = Intent(Intent.ACTION_VIEW).apply {
                                    // Use the Uri where the image was saved
                                    setDataAndType(uri, "image/jpeg") // MIME type for images
                                    flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                                }
                                //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                context.startActivity(createChooser(intent, "Open image with"))

                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                            Toast.makeText(context, "Error downloading image", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            })
    }
    override fun getItemCount(): Int = imageUrls.size
}
