package com.zxhyis.tools.ui.home

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.NonNull
import androidx.annotation.RequiresApi
import androidx.appcompat.widget.PopupMenu
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.zxhyis.tools.R
import com.zxhyis.tools.base.TopFragment
import com.zxhyis.tools.databinding.FragmentViewBinding
import com.zxhyis.tools.logic.Counts
import com.zxhyis.tools.logic.FileBean
import com.zxhyis.tools.logic.Logic
import com.zxhyis.tools.logic.OnItemClickListener
import com.zxhyis.tools.logic.setOnClick
import com.zxhyis.tools.logic.setStatusBarTextDark
import com.zxhyis.tools.logic.testLog
import com.zxhyis.tools.ui.adapter.FileAdapter
import com.zxhyis.tools.ui.dialog.LoadingDialog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.BasicFileAttributes
import java.sql.Date
import java.text.SimpleDateFormat


class ViewFragment : TopFragment<FragmentViewBinding>() {

    private val result =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {}
    private val dataList = ArrayList<FileBean>()
    private val selectedDataList = ArrayList<FileBean>()
    private lateinit var fileAdapter: FileAdapter
    private var dialog: LoadingDialog? = null
    private var needRefresh = false


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

    override fun createBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentViewBinding {
        return FragmentViewBinding.inflate(inflater, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
    }


    private fun showMenu(v:View){
        val popupMenu=PopupMenu(requireActivity(),  v,0,0,R.style.CustomPopupMenu)
        popupMenu.apply {
            menuInflater.inflate(R.menu.select_menu,popupMenu.menu)
            for (i in 0 until menu.size()){
                val menuItem = menu.getItem(i)
                val spannableString = SpannableString(menuItem.title)
                spannableString.setSpan(ForegroundColorSpan(Color.WHITE), 0, spannableString.length, 0)
                menuItem.title = spannableString
            }
            setOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener { item ->
                when (item.itemId) {
                    R.id.item_edit -> {
                        needRefresh = true
                        mK.inView.ivBack.visibility = View.GONE
                        mK.inView.tvMenu.visibility = View.GONE
                        mK.inView.imageSelectAll.visibility = View.VISIBLE
                        mK.llBottom.visibility = View.GONE
                        mK.inView.tvTitle.text = getString(R.string.select_project)
                        fileAdapter.setShow()
                        return@OnMenuItemClickListener true
                    }
                    R.id.item_folder -> {
                        return@OnMenuItemClickListener true
                    }
                    R.id.item_share -> {
                        return@OnMenuItemClickListener true
                    }
                }
                false
            })
            show()
        }
    }

    private fun init() {
        mK.inView.tvTitle.text = getString(R.string.tv_view)
        mK.inView.ivBack.visibility = View.GONE

        mK.tvSet.setOnClick {
            mK.tvSet.setBackgroundResource(R.drawable.bg_shape_set_click)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                result.launch(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION))
            } else {
                ActivityCompat.requestPermissions(
                    requireActivity(),
                    arrayOf(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    ), Counts.REQUEST_ALL_FILE
                )
            }
        }

        mK.inView.tvMenu.setOnClickListener {
            showMenu(it)
        }


        mK.inView.imageSelectAll.setOnClick {
            selectedDataList.clear()
            mK.inView.imageSelectAll.isSelected = !mK.inView.imageSelectAll.isSelected
            if (mK.inView.imageSelectAll.isSelected) {
                fileAdapter.setAllSelected()
            } else {
                fileAdapter.setEmptySelected()
            }
        }


        requireActivity().onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {

            }

        })


    }

    private fun initRv() {
        CoroutineScope(Dispatchers.IO).launch {
            delay(500)
            val currentDir = Environment.getExternalStorageDirectory()
            val files = currentDir.listFiles()
            if (files!=null){
                for (file in files) {
                    if (!file.isHidden && !file.name.startsWith(".") && file.name != ".face") {
                        testLog(file.name)
                        dataList.add(
                            FileBean(
                                file.absolutePath,
                                file,
                                file.name,
                                file.length(),
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) getFileCreationTime(
                                    file.absolutePath
                                )
                                else ""
                            )
                        )
                    }
                }
            }

            fileAdapter = FileAdapter(dataList, requireActivity(), object : OnItemClickListener {
                override fun onItemClick(file: File) {

                }
            }, object : Logic {
                override fun doLogic() {

                }

            })
            launch(Dispatchers.Main) {
                if (dataList.size > 0) {
                    val linearLayoutManager = LinearLayoutManager(requireActivity())
                    linearLayoutManager.initialPrefetchItemCount = 10
                    mK.rvAll.apply {
                        layoutManager = linearLayoutManager
                        setHasFixedSize(true)
                        setItemViewCacheSize(20)
                        adapter = fileAdapter
                    }
                    dialog?.dismiss()
                } else {
                    mK.apply {
                        rvAll.visibility = View.GONE
                        icNoFile.visibility = View.VISIBLE
                        tvNoFile.visibility = View.VISIBLE
                    }
                }
            }
        }
    }

    private fun remove() {

    }

    @SuppressLint("SimpleDateFormat")
    @RequiresApi(Build.VERSION_CODES.O)
    fun getFileCreationTime(filePath: String): String? {
        try {
            val path = Paths.get(filePath)
            val attr = Files.readAttributes(path, BasicFileAttributes::class.java)
            val creationTime = attr.creationTime()
            val date = Date(creationTime.toMillis())
            val format = SimpleDateFormat("yyyy-MM-dd HH:mm")
            return format.format(date)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    override fun onResume() {
        super.onResume()
        requireActivity().window.statusBarColor = 0xFFFFFF
        setStatusBarTextDark(requireActivity())
        dataList.clear()
        selectedDataList.clear()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                mK.apply {
                    mK.inView.ivBack.visibility = View.GONE
                    mK.inView.tvMenu.visibility = View.VISIBLE
                    mK.inView.imageSelectAll.visibility = View.GONE
                    mK.llBottom.visibility = View.GONE
                    imagePer.visibility = View.GONE
                    tvDes.visibility = View.GONE
                    tvSet.visibility = View.GONE
                    rvAll.visibility = View.VISIBLE
                    tvName.visibility = View.VISIBLE
                }
                initRv()
                dialog = LoadingDialog()
                dialog?.isCancelable = false
                dialog?.showNow(childFragmentManager, "loading")
            } else {
                mK.apply {
                    imagePer.visibility = View.VISIBLE
                    tvDes.visibility = View.VISIBLE
                    tvSet.visibility = View.VISIBLE
                    mK.tvSet.setBackgroundResource(R.drawable.bg_shape_set)
                    rvAll.visibility = View.GONE
                    tvName.visibility = View.GONE
                }
            }
        } else {
            if (ContextCompat.checkSelfPermission(
                    requireActivity(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                mK.apply {
                    imagePer.visibility = View.VISIBLE
                    tvDes.visibility = View.VISIBLE
                    tvSet.visibility = View.VISIBLE
                    mK.tvSet.setBackgroundResource(R.drawable.bg_shape_set)
                    rvAll.visibility = View.GONE
                    tvName.visibility = View.GONE
                }
            } else {
                mK.apply {
                    mK.inView.ivBack.visibility = View.GONE
                    mK.inView.tvMenu.visibility = View.VISIBLE
                    mK.inView.imageSelectAll.visibility = View.GONE
                    mK.llBottom.visibility = View.GONE
                    imagePer.visibility = View.GONE
                    tvDes.visibility = View.GONE
                    tvSet.visibility = View.GONE
                    rvAll.visibility = View.VISIBLE
                    tvName.visibility = View.VISIBLE
                    initRv()
                    dialog = LoadingDialog()
                    dialog?.isCancelable = false
                    dialog?.showNow(childFragmentManager, "loading")
                }
            }


        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (dialog != null) {
            dialog?.dismiss()
        }
    }

}