package com.ux.video.file.filerecovery.result

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Environment
import android.view.LayoutInflater
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.ux.video.file.filerecovery.R
import com.ux.video.file.filerecovery.base.BaseActivity
import com.ux.video.file.filerecovery.databinding.ActivityScanningBinding
import com.ux.video.file.filerecovery.utils.Common
import com.ux.video.file.filerecovery.utils.FileType
import com.ux.video.file.filerecovery.utils.ScanManager
import com.ux.video.file.filerecovery.utils.ScanState
import com.ux.video.file.filerecovery.utils.ScanType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch

class ScanningActivity : BaseActivity<ActivityScanningBinding>() {

    private val viewModel: ScanningActivityViewModel by viewModels()
    private lateinit var scanType: ScanType
    override fun inflateBinding(inflater: LayoutInflater): ActivityScanningBinding =
        ActivityScanningBinding.inflate(inflater)

    override fun initData() {
        super.initData()
        val typeValue = intent.getIntExtra(Common.KEY_SCAN_TYPE, ScanType.ALL_PHOTO.value)
        scanType = ScanType.from(typeValue)!!
        setSelectType(scanType)
        if (scanType.isDeletedScan) {
            scanDeleted()
        } else {
            scanAll()
        }
        binding.imageViewBack.setOnClickListener { finish() }

    }

    private fun setSelectType(scanType: ScanType) {
        binding.run {
            when (scanType.mediaType) {
                FileType.PHOTO->{
                    title.text = getString(R.string.photo_title)
                    scanProgress.setCenterImage(R.drawable.im_photo_center_image)
                    if(scanType.isDeletedScan){
                        tvScanDescribe.text = getString(R.string.describe_delete_photos)
                    }else{
                        tvScanDescribe.text = getString(R.string.describe_photos)
                    }
                }
                FileType.VIDEO->{
                    title.text = getString(R.string.video_title)
                    scanProgress.setCenterImage(R.drawable.im_video_center_image)
                    if(scanType.isDeletedScan){
                        tvScanDescribe.text = getString(R.string.describe_delete_videos)
                    }else{
                        tvScanDescribe.text = getString(R.string.describe_videos)
                    }
                }

                FileType.AUDIO->{
                    title.text = getString(R.string.audio_title)
                    scanProgress.setCenterImage(R.drawable.im_audio_center_image)
                    if(scanType.isDeletedScan){
                        tvScanDescribe.text = getString(R.string.describe_delete_audios)
                    }else{
                        tvScanDescribe.text = getString(R.string.describe_audios)
                    }
                }
                FileType.DOCUMENT->{
                    title.text = getString(R.string.document_title)
                    scanProgress.setCenterImage(R.drawable.im_documents_center_image)
                    if(scanType.isDeletedScan){
                        tvScanDescribe.text = getString(R.string.describe_delete_documents)
                    }else{
                        tvScanDescribe.text = getString(R.string.describe_documents)
                    }
                }
            }
        }


    }

    private fun scanAll() {
        val total = 800
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                val root = Environment.getExternalStorageDirectory()
                ScanManager.scanAllDocuments(this@ScanningActivity, root, fileType = scanType.mediaType)
                    .flowOn(Dispatchers.IO).collect {
                        when (it) {
                            is ScanState.Progress -> {
                                updateProgress(it)
                            }

                            is ScanState.Complete -> {
                                updateComplete(it)
                            }
                        }
                    }
            }
        }
    }

    private fun scanDeleted() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                val root = Environment.getExternalStorageDirectory()
                ScanManager.scanHiddenPhotoAsync(this@ScanningActivity, root, fileType = scanType.mediaType)
                    .flowOn(Dispatchers.IO).collect {
                        when (it) {
                            is ScanState.Progress -> {
                                updateProgress(it)

                            }

                            is ScanState.Complete -> {
                                updateComplete(it)
                            }
                        }
                    }
            }

        }

    }


    private fun updateProgress(scanState: ScanState.Progress) {
        val total = 1000
        scanState.let {
            binding.run {
                val percent = (it.scannedCount * 100 / total).coerceAtMost(100)
                scanProgress.setProgress(percent)
                tvScanCurrentFilePath.text = it.filePath
                tvScanCurrentCounts.text = it.scannedCount.toString()
                ScanManager.showLog("Scan", it.filePath)
            }
            ScanManager.showLog(
                "HiddenScan",
                "进度: ${it.scannedCount}"
            )
        }

    }

    @SuppressLint("SetTextI18n")
    private fun updateComplete(scanState: ScanState.Complete) {
        binding.run {
            scanProgress.setProgress(100)
            scanState.let {
                val size = it.result.size
                if (size == 0) {
                    tvScanDescribe.text.let {
                        tvEmptyTypeFile.text = "0 $it"
                        tvSorry.text = getString(R.string.not_found, it)
                    }
                    relativeScanFinishedEmpty.isVisible = true
                    linearCounts.isVisible = false
                } else {
                    finish()
                    viewModel.updateData(it.result)
                    startActivity(
                        Intent(
                            this@ScanningActivity,
                            ScanResultDisplayActivity::class.java
                        ).apply {
                            putExtra(Common.KEY_SCAN_TYPE, scanType.value)
                        })
                }
                ScanManager.showLog("HiddenScan", "完成: ${it.result.size}")
            }
        }
    }

}