package it.danieleverducci.openweddingapp

import android.app.Service
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Parcelable
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.snackbar.Snackbar
import it.danieleverducci.openweddingapp.databinding.ActivityShareBinding
import it.danieleverducci.openweddingapp.databinding.FragmentPresenceBinding
import it.danieleverducci.openweddingapp.entities.GalleryItem
import it.danieleverducci.openweddingapp.networking.GalleryItemNet
import it.danieleverducci.openweddingapp.ui.gallery.GalleryFragment
import it.danieleverducci.openweddingapp.utils.FileUtils
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.*

class ShareActivity: AppCompatActivity() {
    companion object {
        val TAG = "ShareActivity"
    }

    protected lateinit var binding: ActivityShareBinding
    protected val uploadQueue = LinkedList<Uri>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityShareBinding.inflate(
            getSystemService(Service.LAYOUT_INFLATER_SERVICE) as LayoutInflater, null, false)
        setContentView(binding.getRoot())

        // Check for image(s) share intents
        if(intent.type?.startsWith("image/") != true) {
            Toast.makeText(this, R.string.photouploading_unsupported, Toast.LENGTH_SHORT).show()
            finish()
            return
        }

        when {
            intent?.action == Intent.ACTION_SEND -> {
                (intent.getParcelableExtra<Parcelable>(Intent.EXTRA_STREAM) as? Uri)?.let {
                    uploadQueue.addLast(it)
                    upload()
                }
            }
            intent?.action == Intent.ACTION_SEND_MULTIPLE -> {
                intent.getParcelableArrayListExtra<Parcelable>(Intent.EXTRA_STREAM)?.let {
                    for (uri in it) {
                        uploadQueue.addLast(uri as Uri)
                    }
                    // Progression bar is not indeterminate
                    binding.shareProgressDet.visibility = View.VISIBLE
                    binding.shareProgressDet.max = uploadQueue.size
                    upload()
                }
            }
        }
    }

    private fun upload() {
        val uri = uploadQueue.pop()

        // Update progression bar
        binding.shareProgressDet.progress = binding.shareProgressDet.max - uploadQueue.size

        val photoFile: File? = try {
            FileUtils.createTempImageFile(this)
        } catch (ex: IOException) {
            Log.e(MainActivity.TAG, "Unable to create temp camera file: ${ex}")
            null
        }
        // Continue only if the File was successfully created
        photoFile?.also {
            val inStr: InputStream? = contentResolver.openInputStream(uri)
            if (inStr == null) {
                Log.e(TAG, "Error occurred while creating file ${uri.toString()}")
            }

            // Copy uri content to temporary file
            val outStr: OutputStream = photoFile.outputStream()
            inStr!!.use { input ->
                outStr.use { output ->
                    input.copyTo(output)
                }
            }

            // Upload file
            val token = (applicationContext as DeRApplication).token?.token
            if (token == null) {
                Log.e(GalleryFragment.TAG, "Unable to post photo: no token!")
                return
            }
            val galleryItemNet = GalleryItemNet(this, token)
            galleryItemNet.uploadItem(
                token,
                it,
                object : GalleryItemNet.OnGalleryItemUploadCompletedListener {
                    override fun OnGalleryItemUploaded(uploadedGi: GalleryItem?, error: String) {
                        if (!error.isEmpty()) {
                            Toast.makeText(applicationContext, "${getString(R.string.upload_galleryitem_error)}: ${error}", Toast.LENGTH_SHORT).show()
                        } else if (uploadedGi == null) {
                            Toast.makeText(applicationContext, getString(R.string.upload_galleryitem_error), Toast.LENGTH_SHORT).show()
                        }
                        // Cleanup
                        photoFile.delete()

                        // Process next photo (if any)
                        if (uploadQueue.size > 0) {
                            upload()
                        } else {
                            onUploadComplete()
                        }

                    }
                }
            )
        }
    }

    protected fun onUploadComplete() {
        binding.shareLoading.visibility = View.GONE
        binding.shareProgressInd.visibility = View.GONE
        binding.shareProgressDet.visibility = View.GONE
        binding.shareComplete.visibility = View.VISIBLE

        Handler(Looper.getMainLooper()).postDelayed({
            finish()
        }, 1000)
    }

}