package com.sketch.ar.artdrawing.importImage

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.ad.toponlibrary.AdManager
import com.sketch.ar.artdrawing.MyApp
import com.sketch.ar.artdrawing.utils.ObjectBoxHelper
import com.sketch.ar.artdrawing.utils.ItemDec
import com.sketch.ar.artdrawing.utils.CommonUtils
import com.sketch.ar.artdrawing.dataBean.DataImport
import com.sketch.ar.artdrawing.info.InfoActivity
import com.sketch.ar.artdrawing.R
import java.io.File
import kotlin.collections.iterator

class ImportImageActivity : 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: ImportTypeDialog? = null
    private lateinit var importImageAdapter: ImportImageAdapter
    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_import_image)
        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
        }

        AdManager.loadAllAd()
        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@ImportImageActivity, " 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 {
            AdManager.showTopOn(this) {
                dialog = dialog ?: ImportTypeDialog { type->
                    if(type == ImportTypeDialog.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@ImportImageActivity, 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 = CommonUtils.getUriFileSize(this@ImportImageActivity, imageUri)
        Log.d(MyApp.Companion.TAG, "------uriFileSize-----$uriFileSize--Mb  imageUri=${imageUri}")
        if (uriFileSize >= 4) {
            loadPb.visibility = View.GONE
            Toast.makeText(
                this@ImportImageActivity,
                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 = CommonUtils.getImportPath(name)
            targetFile = targetFilePath?.let { File(it) }

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


    private fun initData() {
        importImageAdapter =
            ImportImageAdapter(this@ImportImageActivity) { isDelete, path->
                if(isDelete){
                    updateUi(importImageAdapter.itemCount > 0)
                }else{
                  startActivity(Intent(this@ImportImageActivity, InfoActivity::class.java).apply {
                        putExtra(InfoActivity.Companion.IntentKeyPath, path)
                    })
                }
            }
        Thread {
            val importUrises = ObjectBoxHelper.queryAllImport()
            runOnUiThread {
                importImageAdapter.updateData(importUrises)
                updateUi(importUrises.size > 0)
                loadPb.visibility = View.GONE
            }
        }.start()
        recyclerView.run {
            val itemDec = ItemDec(5, 5, 0)
            addItemDecoration(itemDec)
            adapter = importImageAdapter
            layoutManager = GridLayoutManager(this@ImportImageActivity, 3)
        }

    }


}