package com.drawing.drawsketch.upload

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
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.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.drawing.drawsketch.App
import com.drawing.drawsketch.DbBase
import com.drawing.drawsketch.ItemSpace
import com.drawing.drawsketch.R
import com.drawing.drawsketch.Utils
import com.drawing.drawsketch.dbmodel.UpLoad
import com.drawing.drawsketch.preview.PreviewActivity
import java.io.File

class UploadActivity : AppCompatActivity() {
    private lateinit var fmBack:FrameLayout
    private lateinit var recyclerView: RecyclerView
    private lateinit var emptyLayout:LinearLayout
    private lateinit var imageUpload:ImageView
    private lateinit var loadPb:ProgressBar



    private lateinit var cameraLauncher: ActivityResultLauncher<Uri>
    private lateinit var cameraPermissionLauncher: ActivityResultLauncher<String>
    private var photoUri: Uri? = null


    private lateinit var permissions: Array<String>
    private var dialog: DialogSelect? = null
    private lateinit var uploadAdapter: UploadAdapter
    private lateinit var galleryLauncher: ActivityResultLauncher<Intent>
    private var storePermissionsLauncher: ActivityResultLauncher<Array<String>>? = null


    private lateinit var cameraFile: File
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_upload)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        recyclerView = findViewById(R.id.list_recyclerview)
        fmBack = findViewById(R.id.frame_back)
        emptyLayout = findViewById(R.id.layout_empty)
        imageUpload = findViewById(R.id.image_upload)
        loadPb= findViewById<ProgressBar>(R.id.loading_pb)
        initLauncher()
        initData()
        setClick()

    }

    private fun initLauncher(){
        cameraPermissionLauncher =
            registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
                if (granted) {
                    takePhoto()
                } else {
                    Toast.makeText(this, getString(R.string.camera_denied), Toast.LENGTH_SHORT).show()
                }
            }
        cameraLauncher =
            registerForActivityResult(ActivityResultContracts.TakePicture()) { success ->
                if (success && photoUri != null) {
                    saveUploadImage(photoUri!!, true)
                }
            }
        storePermissionsLauncher = registerForActivityResult<Array<String>, Map<String, Boolean>>(
            ActivityResultContracts.RequestMultiplePermissions()

        ) {
            var isGranted = true
            for ((string, value) in it) {
                if (!value) {
                    isGranted = false
                }

            }
            if (isGranted) {
                takeGallery()
            } else {
                Toast.makeText(this@UploadActivity, " Permission denied", Toast.LENGTH_SHORT)
                    .show()
            }
        }
        galleryLauncher = registerForActivityResult<Intent, ActivityResult>(
            ActivityResultContracts.StartActivityForResult()
        ) { result: ActivityResult ->
            if (result.resultCode == RESULT_OK && result.data != null) {
                val imageUri = result.data!!.data
                imageUri?.let { saveUploadImage(it) }
            }
        }
    }
    private fun setClick(){
        fmBack.setOnClickListener {
            finish()
        }
        imageUpload.setOnClickListener {
            dialog = dialog ?: DialogSelect { type->
                if(type == DialogSelect.TYPE_CAMERA){
                    openCamera()
                }else{
                    openGallery()
                }

            }
            dialog!!.show(supportFragmentManager, "")
        }
    }



    private fun updateUi(isShow: Boolean) {
        if (isShow) {
            recyclerView.visibility = View.VISIBLE
            emptyLayout.visibility = View.GONE
        } else {
            recyclerView.visibility = View.GONE
            emptyLayout.visibility = View.VISIBLE
        }
    }


    private fun openGallery() {
        permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arrayOf(Manifest.permission.READ_MEDIA_IMAGES)
        } else {
            arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        }
        val notGranted = permissions.filter {
            ContextCompat.checkSelfPermission(this@UploadActivity, it) != PackageManager.PERMISSION_GRANTED
        }
        if (notGranted.isNotEmpty()) {
            storePermissionsLauncher!!.launch(permissions)
        } else {
            takeGallery()
        }
    }

    private fun takeGallery() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        intent.type = "image/*"
        galleryLauncher.launch(intent)
    }

    private fun openCamera() {
        val permission = Manifest.permission.CAMERA
        if (ContextCompat.checkSelfPermission(
                this,
                permission
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            cameraPermissionLauncher.launch(permission)
        } else {
            takePhoto()
        }
    }

    private fun takePhoto() {
        cameraFile = File.createTempFile("IMG_", ".jpg", cacheDir)
        photoUri = FileProvider.getUriForFile(this, "${packageName}.fileprovider", cameraFile)
        cameraLauncher.launch(photoUri!!)

    }


    private fun saveUploadImage(imageUri: Uri, isCamera: Boolean = false) {
        var targetFile: File? = null
        var targetFilePath: String? = null
        loadPb.visibility = View.VISIBLE
        val uriFileSize = Utils.getUriFileSize(this@UploadActivity, imageUri)
        Log.d(App.TAG, "------uriFileSize-----$uriFileSize--Mb  imageUri=${imageUri}")
        if (uriFileSize >= 4) {
            loadPb.visibility = View.GONE
            Toast.makeText(
                this@UploadActivity,
                getString(R.string.import_im_too_big),
                Toast.LENGTH_SHORT
            ).show()
            return
        }

        if (isCamera) {
            if (cameraFile.exists()) {
                targetFile = cameraFile
                targetFilePath = cameraFile.absolutePath
            }
        } else {
            //相册导入的照片，构建同名文件放在files目录下，并且复制图片到这个目录下
            val lastPathSegment: String = imageUri.lastPathSegment!!
            val index = lastPathSegment.lastIndexOf("/")
            val name = lastPathSegment.substring(index + 1)
            targetFilePath = Utils.getImportPath(name)
            targetFile = targetFilePath?.let { File(it) }

        }
        Log.d(
            App.TAG,
            "------targetFilePath-----$targetFilePath-- targetFile.name=${targetFile?.name}"
        )
        val isimport = DbBase.queryIsImport(targetFilePath)
        Thread {
            if (targetFile!!.exists()) {
                if (!isimport) {
                    DbBase.insertImport(targetFilePath)
                }
                runOnUiThread(Runnable {
                    loadPb.visibility = View.GONE
                    if (isimport) {
                        Toast.makeText(
                            this@UploadActivity,
                            getString(R.string.import_already),
                            Toast.LENGTH_SHORT
                        ).show()
                    } else {
                        val beanUpload = UpLoad()
                        beanUpload.uri = targetFilePath
                        uploadAdapter.addData(listOf(beanUpload))
                        updateUi(true)
                    }
                })
            } else {
                Log.d(App.TAG, "---------------------else   targetFile.name=${targetFile.name}")
                //复制图片到files目录下
                val b = Utils.saveToStorage(
                    targetFile.name,
                    imageUri,
                    this@UploadActivity
                )
                if (b) {
                    DbBase.insertImport(targetFilePath)
                }
                runOnUiThread {
                    loadPb.visibility = View.GONE
                    if (b) {
                        val beanUpload = UpLoad()
                        beanUpload.uri = targetFilePath
                        uploadAdapter.addData(listOf(beanUpload))
                        updateUi(true)
                    } else {
                        Toast.makeText(
                            this,
                            getString(R.string.upload_fail),
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            }
        }.start()
    }


    private fun initData() {
        uploadAdapter =
            UploadAdapter(this@UploadActivity) { isDelete,path->
                if(isDelete){
                    updateUi(uploadAdapter.itemCount > 0)
                }else{
                  startActivity(Intent(this@UploadActivity, PreviewActivity::class.java).apply {
                        putExtra(PreviewActivity.IntentKeyPath, path)
                    })
                }
            }
        Thread {
            val importUrises = DbBase.queryAllImport()
            runOnUiThread {
                uploadAdapter.updateData(importUrises)
                updateUi(importUrises.size > 0)
                loadPb.visibility = View.GONE
            }
        }.start()
        recyclerView.run {
            val itemSpace = ItemSpace(5, 5, 0)
            addItemDecoration(itemSpace)
            adapter = uploadAdapter
            layoutManager = GridLayoutManager(this@UploadActivity, 3)
        }

    }


}