package com.base.filerecoveryrecyclebin.fragment

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.view.View
import androidx.annotation.RequiresApi
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.base.filerecoveryrecyclebin.activity.MainActivity
import com.base.filerecoveryrecyclebin.activity.recyclebin.MyFileObserver.Companion.getRecycleBinDir
import com.base.filerecoveryrecyclebin.activity.recyclebin.RecycleBinDetailActivity
import com.base.filerecoveryrecyclebin.adapter.RecycleBinAdapter
import com.base.filerecoveryrecyclebin.bean.RecycleBinBean
import com.base.filerecoveryrecyclebin.databinding.FragmentRecycleBinBinding
import com.base.filerecoveryrecyclebin.help.BaseFragment
import com.base.filerecoveryrecyclebin.help.PermissionHelp.checkStorePermission
import com.base.filerecoveryrecyclebin.help.PermissionHelp.requestStorePermission
import com.base.filerecoveryrecyclebin.service.StayNotificationService
import com.base.filerecoveryrecyclebin.utils.LogEx
import com.base.filerecoveryrecyclebin.view.DialogViews.showGerPermission
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

class RecycleBinFragment : BaseFragment<FragmentRecycleBinBinding>() {

    private val TAG = "RecycleBinFragment"
    private lateinit var handler: Handler
    private lateinit var recycleBinAdapter: RecycleBinAdapter

    override val binding: FragmentRecycleBinBinding by lazy {
        FragmentRecycleBinBinding.inflate(layoutInflater)
    }

    @RequiresApi(Build.VERSION_CODES.Q)
    override fun setView() {

        handler = Handler(requireActivity().mainLooper) { message ->
            if (message.what == 99) {
//                LogEx.logDebug(TAG, "媒体库更新了")
                initData()
            }
            if (message.what == 100) {
//                LogEx.logDebug(TAG, "回收站数据更新了")
                initData()
            }
            true
        }
        StayNotificationService.mainHandler = handler

        requireActivity().startService(Intent(requireActivity(), StayNotificationService::class.java).apply {
            this.action = StayNotificationService.MEDIA_OBSERVER_ACTION
        })
        requireActivity().startService(Intent(requireContext(), StayNotificationService::class.java).apply {
            this.action = StayNotificationService.FILE_OBSERVER_ACTION
            putExtra("isStart", true)
        })
        recycleBinAdapter = RecycleBinAdapter { bean ->
            startActivity(Intent(requireContext(), RecycleBinDetailActivity::class.java).apply {
                putExtra("Json", Gson().toJson(bean))
            })
        }
        binding.rv.adapter = recycleBinAdapter

        val launcher = (requireActivity() as MainActivity).launcher
        if (requireActivity().checkStorePermission()) {
            initData()
        } else {
            requireContext().showGerPermission(allow = {
                requireContext().requestStorePermission(launcher, result = { flag ->
                    if (flag) {
                        initData()
                    }
                })
            })
        }
    }

    override fun setListener() {
        super.setListener()
        binding.flGengduo.setOnClickListener {

        }
        binding.swipeRefreshLayout.setOnRefreshListener {
            binding.swipeRefreshLayout.isRefreshing = true
            initData()
            lifecycleScope.launch(Dispatchers.Main) {
                delay(1000)
                binding.swipeRefreshLayout.isRefreshing = false
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.Q)
    private fun initData() {
        lifecycleScope.launch(Dispatchers.IO) {

            val binList = getRecycleBinDir().listFiles()?.filter { it.name.contains(".bin") }
            val beanList = arrayListOf<RecycleBinBean>()
            binList?.forEach {
                LogEx.logDebug(TAG, it.absolutePath)
                val bean = Gson().fromJson(it.readText(), RecycleBinBean::class.java)
                beanList.add(bean)
            }
            val deleteFile = beanList.filter { it.deleted }
//            val deleteFile = beanList
            launch(Dispatchers.Main) {
                binding.rv.isVisible = deleteFile.isNotEmpty()
                binding.llEmpty.isVisible = deleteFile.isEmpty()
                recycleBinAdapter.setData(deleteFile)
            }

        }
    }


}