package com.zxhy.solarmasterace.tools

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.zxhy.solarmasterace.R
import com.zxhy.solarmasterace.databinding.FragmentToolsBinding
import com.zxhy.solarmasterace.datastore.DUP_IMAGE_COUNTER_KEY
import com.zxhy.solarmasterace.datastore.EMPTY_FILE_COUNTER_KEY
import com.zxhy.solarmasterace.datastore.LARGE_FILES_COUNTER_KEY
import com.zxhy.solarmasterace.datastore.queryFileCount
import com.zxhy.solarmasterace.datastore.saveFileCount
import com.zxhy.solarmasterace.filedetails.FileDetailActivity
import com.zxhy.solarmasterace.quicktools.getFilePathByUri
import com.zxhy.solarmasterace.quicktools.recentImage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import java.io.File

class ToolsFragment : Fragment() {

    private lateinit var binding: FragmentToolsBinding
    private lateinit var imageAdapter: RecentImageAdapter
    private lateinit var context: Context

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val root = inflater.inflate(R.layout.fragment_tools, container, false)
        binding = FragmentToolsBinding.bind(root)
        return root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        context = requireContext()
        imageAdapter = RecentImageAdapter { uri ->
            lifecycleScope.launch(Dispatchers.Main) {
                var path = ""
                async(Dispatchers.IO) {
                    path = getFilePathByUri(context, uri) ?: ""
                }.await()
                if (File(path).exists()) {
                    startActivity(Intent(context, FileDetailActivity::class.java).apply {
                        putExtra("Path", path)
                    })
                }
            }


        }
        binding.rv.adapter = imageAdapter
        binding.cardDupImage.setOnClickListener {
            val bundle = Bundle().apply {
                putString("tittle", "Duplicate picture")
            }
            findNavController().navigate(R.id.fileBrowserActivity, bundle)
        }
        binding.cardLargeImage.setOnClickListener {
            val bundle = Bundle().apply {
                putString("tittle", "Scan large files")
            }
            findNavController().navigate(R.id.fileBrowserActivity, bundle)
        }
        binding.cardEmptyFile.setOnClickListener {
            val bundle = Bundle().apply {
                putString("tittle", "Scan empty file")
            }
            findNavController().navigate(R.id.fileBrowserActivity, bundle)
        }

        loadRecentImage()
        queryFileCounts()
    }

    @SuppressLint("SetTextI18n")
    private fun queryFileCounts() {
        lifecycleScope.launch(Dispatchers.Main) {
//            context.saveFileCount(DUP_IMAGE_COUNTER_KEY, 100)
            context.queryFileCount(DUP_IMAGE_COUNTER_KEY) { count ->
                if (count == 0) {
                    binding.tvDupCout.visibility = View.GONE
                } else {
                    binding.tvDupCout.visibility = View.VISIBLE
                    binding.tvDupCout.text = "$count items"
                }
            }
        }

        lifecycleScope.launch(Dispatchers.Main) {
//            context.saveFileCount(LARGE_FILES_COUNTER_KEY, 200)
            context.queryFileCount(LARGE_FILES_COUNTER_KEY) { count ->
                if (count == 0) {
                    binding.tvLargeCount.visibility = View.GONE
                } else {
                    binding.tvLargeCount.visibility = View.VISIBLE
                    binding.tvLargeCount.text = "$count items"
                }
            }


        }
        lifecycleScope.launch(Dispatchers.Main) {
//            context.saveFileCount(EMPTY_FILE_COUNTER_KEY, 300)
            context.queryFileCount(EMPTY_FILE_COUNTER_KEY) { dupCount ->
                if (dupCount == 0) {
                    binding.tvEmptyCount.visibility = View.GONE
                } else {
                    binding.tvEmptyCount.visibility = View.VISIBLE
                    binding.tvEmptyCount.text = "$dupCount items"
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        loadRecentImage()
    }

    private fun loadRecentImage() {
        lifecycleScope.launch(Dispatchers.IO) {
            val list = recentImage(context)
            launch(Dispatchers.Main) {
                imageAdapter.setData(list)
            }
        }
    }



    companion object {
        @JvmStatic
        fun newInstance() =
            ToolsFragment().apply {
                arguments = Bundle().apply {
                }
            }
    }
}