package com.zxhyis.tools.ui.home

import android.Manifest
import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.StatFs
import android.provider.MediaStore
import android.provider.Settings
import android.text.format.Formatter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
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.FragmentHomeBinding
import com.zxhyis.tools.logic.Counts
import com.zxhyis.tools.logic.ImageAndVideoBean
import com.zxhyis.tools.logic.setOnClick
import com.zxhyis.tools.logic.setStatusBarTextDark
import com.zxhyis.tools.logic.setStatusBarTextLight
import com.zxhyis.tools.logic.startActivity
import com.zxhyis.tools.ui.adapter.HomeAdapter
import com.zxhyis.tools.ui.`fun`.ApkListActivity
import com.zxhyis.tools.ui.`fun`.AudioActivity
import com.zxhyis.tools.ui.`fun`.DocumentsActivity
import com.zxhyis.tools.ui.`fun`.EmptyFileActivity
import com.zxhyis.tools.ui.`fun`.LargeFilesActivity
import com.zxhyis.tools.ui.`fun`.PictureActivity
import com.zxhyis.tools.ui.`fun`.RecentlyActivity
import com.zxhyis.tools.ui.`fun`.VideoActivity
import com.zxhyis.tools.ui.`fun`.ZipFileActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File


class HomeFragment : TopFragment<FragmentHomeBinding>() {

    private lateinit var homeAdapter: HomeAdapter
    private val dataList = ArrayList<ImageAndVideoBean>()
    private val result =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {}


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

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

    private fun init() {
        val activityManager = requireActivity().getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val memoryInfo = ActivityManager.MemoryInfo()
        activityManager.getMemoryInfo(memoryInfo)
        val totalMemory =memoryInfo.totalMem
        val availableMemory = memoryInfo.availMem
        val usedMemory=totalMemory-availableMemory
        val usedPercentage = usedMemory.toFloat() / totalMemory * 100
        mK.pb.progress = usedPercentage.toInt()
        mK.tvProgress.text = "${usedPercentage.toInt()}"
        mK.tvFreeSize.text = Formatter.formatFileSize(requireActivity(), availableMemory)
        mK.tvUsedSize.text = Formatter.formatFileSize(requireActivity(), usedMemory)

        mK.clsPicture.setOnClick {
            mK.clsPicture.setBackgroundResource(R.drawable.bg_shape_home_item_click)
            requireActivity().startActivity<PictureActivity>()
        }
        mK.clsVideo.setOnClick {
            mK.clsVideo.setBackgroundResource(R.drawable.bg_shape_home_item_click)
            requireActivity().startActivity<VideoActivity>()
        }
        mK.clsAudio.setOnClick {
            mK.clsAudio.setBackgroundResource(R.drawable.bg_shape_home_item_click)
            requireActivity().startActivity<AudioActivity>()
        }
        mK.clsApk.setOnClick {
            mK.clsApk.setBackgroundResource(R.drawable.bg_shape_home_item_click)
            requireActivity().startActivity<ApkListActivity>()
        }
        mK.clsEmpty.setOnClick {
            mK.clsEmpty.setBackgroundResource(R.drawable.bg_shape_home_item_click)
            requireActivity().startActivity<EmptyFileActivity>()
        }

        mK.clsLarge.setOnClick {
            mK.clsLarge.setBackgroundResource(R.drawable.bg_shape_home_item_click)
            requireActivity().startActivity<LargeFilesActivity>()
        }
        mK.clsZip.setOnClick {
            mK.clsZip.setBackgroundResource(R.drawable.bg_shape_home_item_click)
            requireActivity().startActivity<ZipFileActivity>()
        }
        mK.clsDoc.setOnClick {
            mK.clsDoc.setBackgroundResource(R.drawable.bg_shape_home_item_click)
            requireActivity().startActivity<DocumentsActivity>()
        }

        mK.btPer.setOnClick {
            mK.btPer.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.tvMore.setOnClick {
            requireActivity().startActivity<RecentlyActivity>()
        }

    }

    override fun onResume() {
        super.onResume()
        requireActivity().window.statusBarColor=ContextCompat.getColor(requireActivity(),R.color.home_top)
        setStatusBarTextDark(requireActivity())
        dataList.clear()
        updateUI()
        setBa()
    }

    private fun updateUI() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                mK.rvRecent.visibility = View.VISIBLE
                mK.btPer.visibility = View.GONE
                initRv()
            } else {
                mK.rvRecent.visibility = View.GONE
                mK.btPer.visibility = View.VISIBLE
            }
        } else {
            if (ContextCompat.checkSelfPermission(
                    requireActivity(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                mK.rvRecent.visibility = View.GONE
                mK.btPer.visibility = View.VISIBLE
            } else {
                mK.rvRecent.visibility = View.VISIBLE
                initRv()
                mK.btPer.visibility = View.GONE
            }
        }
    }

    @SuppressLint("Recycle")
    private fun initRv() {
        CoroutineScope(Dispatchers.IO).launch {
            delay(500)
            val contentResolver = requireActivity().contentResolver
            val imagesUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            val videosUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
            val projection =
                arrayOf(MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DATE_ADDED)
            val sortOrder = "${MediaStore.MediaColumns.DATE_ADDED} DESC"
            val cursorImages = contentResolver.query(imagesUri, projection, null, null, sortOrder)
            val cursorVideos = contentResolver.query(videosUri, projection, null, null, sortOrder)

            cursorImages?.use { cursor ->
                val columnIndexData = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
                while (cursor.moveToNext()) {
                    val imagePath = cursor.getString(columnIndexData)
                    val file = File(imagePath)
                    dataList.add(
                        ImageAndVideoBean(
                            imagePath,
                            file,
                            1
                        )
                    )
                }
            }
            cursorVideos?.use { cursor ->
                val columnIndexData = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
                while (cursor.moveToNext()) {
                    val videoPath = cursor.getString(columnIndexData)
                    val file = File(videoPath)
                    dataList.add(
                        ImageAndVideoBean(
                            videoPath,
                            file,
                            2
                        )
                    )
                }
            }
            cursorImages?.close()
            cursorVideos?.close()
            homeAdapter = HomeAdapter(dataList)
            launch(Dispatchers.Main) {
                if (dataList.size>0){
                    val linearLayoutManager = LinearLayoutManager(requireActivity(),LinearLayoutManager.HORIZONTAL,false)
                    linearLayoutManager.initialPrefetchItemCount=3
                    mK.rvRecent.apply {
                        layoutManager=linearLayoutManager
                        setHasFixedSize(true)
                        setItemViewCacheSize(20)
                        adapter = homeAdapter
                    }
                    mK.btPer.visibility=View.GONE
                    mK.rvRecent.visibility=View.VISIBLE
                    mK.noFile.visibility=View.GONE
                }else{
                   mK.btPer.visibility=View.GONE
                   mK.rvRecent.visibility=View.GONE
                   mK.noFile.visibility=View.VISIBLE
                }
            }
        }
    }

    private fun setBa() {
        mK.clsPicture.setBackgroundResource(R.drawable.bg_shape_home_item)
        mK.clsVideo.setBackgroundResource(R.drawable.bg_shape_home_item)
        mK.clsAudio.setBackgroundResource(R.drawable.bg_shape_home_item)
        mK.clsApk.setBackgroundResource(R.drawable.bg_shape_home_item)
        mK.clsZip.setBackgroundResource(R.drawable.bg_shape_home_item)
        mK.clsEmpty.setBackgroundResource(R.drawable.bg_shape_home_item)
        mK.clsLarge.setBackgroundResource(R.drawable.bg_shape_home_item)
        mK.clsDoc.setBackgroundResource(R.drawable.bg_shape_home_item)
        mK.btPer.setBackgroundResource(R.drawable.bg_shape_set)
    }


}