package com.test.mydemo3.fragment

import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import androidx.fragment.app.viewModels
import android.os.Bundle
import android.os.Environment
import android.os.StatFs
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import com.test.mydemo3.R
import com.test.mydemo3.activity.BatteryActivity
import com.test.mydemo3.activity.CleanActivity
import com.test.mydemo3.activity.SimilarImagesActivity
import com.test.mydemo3.activity.ScanEmptyFilesActivity
import com.test.mydemo3.activity.ScanLargeFilesActivity
import com.test.mydemo3.antivirus.AntivirusActivity
import com.test.mydemo3.util.PermissionUtil
import com.test.mydemo3.view.CirclePgBar
import com.test.mydemo3.view.CustomDialog

class HomeFragment : Fragment(), OnClickListener{
    private lateinit var mView: View
    private lateinit var mScanLargeFiles: LinearLayout
    private lateinit var mScanPictureFiles: LinearLayout
    private lateinit var mScanEmptyFiles: LinearLayout
    private lateinit var mProgressText: TextView
    private lateinit var mUseStorageText: TextView
    private lateinit var mUseStorageProgress: ProgressBar
    private lateinit var mMemoryUseText: TextView
    private lateinit var mMemoryUseProgress: ProgressBar
    private lateinit var mBatteryInfo: View
    private lateinit var mCirclePgBar: CirclePgBar
    companion object {
        fun newInstance() = HomeFragment()
    }

    private val viewModel: HomeViewModel by viewModels()

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

        // TODO: Use the ViewModel
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mView = inflater.inflate(R.layout.fragment_home, container, false)
        initView()
        return mView
    }

    private fun initView() {
        mScanLargeFiles = mView.findViewById(R.id.scan_large_files)
        mScanPictureFiles = mView.findViewById(R.id.scan_for_duplicate_picture)
        mScanEmptyFiles = mView.findViewById(R.id.scan_empty_files)
        mProgressText = mView.findViewById(R.id.scan_progress_text)
        mBatteryInfo = mView.findViewById(R.id.battery_info)

        mUseStorageText = mView.findViewById(R.id.use_storage_text)
        mMemoryUseText = mView.findViewById(R.id.memory_used_text)

        mUseStorageProgress = mView.findViewById(R.id.use_storage_progress)
        mMemoryUseProgress = mView.findViewById(R.id.memory_used_progress)
        mCirclePgBar = mView.findViewById(R.id.progress_circular)

        setUseStorage()
        setMemoryUsagePercentage()

        mScanPictureFiles.setOnClickListener(this)
        mScanLargeFiles.setOnClickListener(this)
        mScanEmptyFiles.setOnClickListener(this)
        mBatteryInfo.setOnClickListener(this)

        mView.findViewById<CirclePgBar>(R.id.progress_circular).setOnClickListener(this)
        mView.findViewById<View>(R.id.home_clean_btn).setOnClickListener(this)
        mView.findViewById<View>(R.id.antivirus_btn).setOnClickListener (this)


    }

    override fun onClick(v: View?) {
        if (checkPermission()){
            when(v?.id){
                R.id.scan_for_duplicate_picture ->{
                    activity?.startActivity(Intent(context, SimilarImagesActivity::class.java))
                }
                R.id.scan_large_files ->{
                    activity?.startActivity(Intent(context, ScanLargeFilesActivity::class.java))
                }
                R.id.scan_empty_files ->{
                    activity?.startActivity(Intent(context, ScanEmptyFilesActivity::class.java))
                }
                R.id.home_clean_btn ->{
                    activity?.startActivity(Intent(context, CleanActivity::class.java))

                }
            }
            if (v?.id == R.id.battery_info){
                activity?.startActivity(Intent(context, BatteryActivity::class.java))
            }else if (v?.id == R.id.antivirus_btn){
                activity?.startActivity(Intent(context, AntivirusActivity::class.java))
            }
        }



    }

    private fun checkPermission(): Boolean {
        if (!PermissionUtil.checkGrantedPermission(activity)) {
            val customDialog = CustomDialog(context)
            customDialog.setsConfirm(OnClickListener {
                PermissionUtil.requestPermission(context)
                customDialog.dismiss()
            }).setsCancel(OnClickListener {
                customDialog.dismiss()
            }).show()
            customDialog.isShowEditText(false)
            customDialog.setsTitle("not permission")
            customDialog.setsHint("Please grant file management permissions")
            return false
        }
        return true
    }

    fun setUseStorage(){

        val storageDirectory = Environment.getExternalStorageDirectory()
        val statFs = StatFs(storageDirectory.path)
        val totalBytes = (statFs.totalBytes / 1024 / 1024).toInt()
        val freeSpase  = (statFs.availableBytes / 1024 /1024).toInt()
        val used = totalBytes - freeSpase

        val sdUsed = ((used.toFloat() / totalBytes.toFloat()) * 100.0)

        mUseStorageText.text = String.format("%.1f", sdUsed)

        mUseStorageProgress.progress = sdUsed.toInt()

        mProgressText.text = String.format("%.1f", sdUsed)

        mCirclePgBar.setTargetProgress(sdUsed.toInt())

    }

    fun setMemoryUsagePercentage(){
        val activityManager = context?.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        Thread(Runnable {
            while (true){
                val memoryInfo = ActivityManager.MemoryInfo()
                activityManager.getMemoryInfo(memoryInfo)

                // 获取系统总内存
                val totalMemory = memoryInfo.totalMem

                // 获取系统剩余内存
                val availableMemory = memoryInfo.availMem

                // 获取系统已用内存
                val usedMemory = totalMemory - availableMemory

                // 计算内存占用率
                val memoryUsagePercentage = (usedMemory.toFloat() / totalMemory.toFloat()) * 100


                activity?.runOnUiThread {
                    mMemoryUseText.text = String.format("%.1f", memoryUsagePercentage)
                    mMemoryUseProgress.progress = (memoryUsagePercentage).toInt()
                }
                Thread.sleep(1000)

            }

        }).start()

    }


}