package com.xd.camerademokotlin

import android.app.Activity
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import java.io.File


class MainActivity : AppCompatActivity() {
    private lateinit var imageView: ImageView
    private lateinit var textView: TextView
    private lateinit var tempImgUri: Uri
    private val tempImgFileName = "xd_temp_img.jpg"
    private lateinit var cameraResult: ActivityResultLauncher<Intent>

    private var line: String? = "..."
    private lateinit var myViewModel: MyViewModel
    private val TEXTVIEW_KEY = "textview_key"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        imageView = findViewById(R.id.imageProfile)
        textView = findViewById(R.id.text_view)

        Util.checkPermissions(this)
        myViewModel = ViewModelProvider(this).get(MyViewModel::class.java)
        myViewModel.userImage.observe(this, { it ->
            imageView.setImageBitmap(it)
        })

//        myViewModel.userImage.observe(this) { it ->
//            imageView.setImageBitmap(it)
//        }

        val tempImgFile = File(getExternalFilesDir(null), tempImgFileName) //XD: try Environment.DIRECTORY_PICTURES instead of "null"
        tempImgUri = FileProvider.getUriForFile(this, "com.xd.camerademokotlin", tempImgFile)
        if(tempImgFile.exists()) {
            val bitmap = Util.getBitmap(this, tempImgUri)
            imageView.setImageBitmap(bitmap)
        }

        cameraResult = registerForActivityResult(StartActivityForResult())
        { result: ActivityResult ->
            if(result.resultCode == Activity.RESULT_OK){
                val bitmap = Util.getBitmap(this, tempImgUri)
                myViewModel.userImage.value = bitmap

                //***
                line = tempImgUri.path.toString()
                textView.setText(line)
            }
        }

        //***
        if(savedInstanceState != null)
            line = savedInstanceState.getString(TEXTVIEW_KEY);

        textView.setText(line)
        //***
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putString(TEXTVIEW_KEY, line)
    }

    fun onChangePhotoClicked(view: View) {
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        intent.putExtra(MediaStore.EXTRA_OUTPUT, tempImgUri)
        cameraResult.launch(intent)
    }

}