package com.test.mydemo3.fragment

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.util.SparseBooleanArray
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ListView
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.kongzue.dialogx.dialogs.WaitDialog
import com.test.mydemo3.MyApplication
import com.test.mydemo3.R
import com.test.mydemo3.activity.BaseActivityViewModel
import com.test.mydemo3.activity.HomeActivity
import com.test.mydemo3.activity.InternalStorageActivity
import com.test.mydemo3.activity.MoveOrCopyActivity
import com.test.mydemo3.adapter.FilesItemViewAdapter
import com.test.mydemo3.base.BaseActivity
import com.test.mydemo3.model.FileBean
import com.test.mydemo3.util.FileUtil
import com.test.mydemo3.util.PermissionUtil
import com.test.mydemo3.view.CustomDialog
import java.io.File

class InternalStorageFragment : Fragment(), View.OnClickListener {

    private lateinit var mView: View
    lateinit var mTitleText: TextView
    lateinit var mShareBtn: ImageView
    lateinit var mDeleteBtn: ImageView
    lateinit var mNewBtn: ImageView
    lateinit var mCancelBtn: ImageView
    lateinit var mQuitBtn: ImageView
    lateinit var mEditBtn: ImageView
    lateinit var mBottomBar: View
    lateinit var mSelectNumText: TextView
    lateinit var mCurrantFilePathTv: TextView

    lateinit var mCheckItemSelectAllBtn: CheckBox

    lateinit var mMoveBottomBtn: LinearLayout
    lateinit var mRenameBottomBtn: LinearLayout
    lateinit var mCopyBottomBtn: LinearLayout
    lateinit var mDeleteBottomBtn: LinearLayout
    lateinit var mCancelBottomBtn: LinearLayout

    lateinit var mSwitchSelectView: RelativeLayout
    lateinit var mNotFileFoundLayout: View
    lateinit var mNotPermissionLayout: View

    private lateinit var mFilesItemListView: ListView

    lateinit var mBaseViewModel : BaseActivityViewModel

    var mFileAdapter: FilesItemViewAdapter? = null
    lateinit var mItemCheckedArray: SparseBooleanArray
    var mFileCheckedItemList = ArrayList<FileBean>()
    var mFilesItemLists = ArrayList<ArrayList<FileBean>>()
    var mCurrentFilePath: String = FileUtil.EXTERNAL_STORAGE
    var mCurrentFileBean: FileBean? = null
    var mTitleStr: String = ""
    companion object{
        var isClickEditBtn = false
        var isClickCheckBoxAllBtn = false
        var switchNumber = 0
        var mCurrentList: ArrayList<FileBean> = ArrayList()
        var mItemDataList: ArrayList<FileBean> = ArrayList()
        val mFileDataBean: ArrayList<FileBean> = ArrayList()

        var isRename = false
        var isMove = false
        var isCopy = false
    }

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

    private fun initView() {

        mBaseViewModel = ViewModelProvider(this)[BaseActivityViewModel::class.java]

        mTitleText = mView.findViewById(R.id.title_bar_text)
        mShareBtn = mView.findViewById(R.id.btn_share)
        mDeleteBtn = mView.findViewById(R.id.btn_delete)
        mNewBtn = mView.findViewById(R.id.btn_new)
        mCancelBtn = mView.findViewById(R.id.btn_cancel)
        mQuitBtn = mView.findViewById(R.id.btn_quit)
        mEditBtn = mView.findViewById(R.id.btn_edit)
        mBottomBar = mView.findViewById(R.id.bottom_btn_group)
        mSwitchSelectView = mView.findViewById(R.id.switch_and_select_layout)
        mSelectNumText = mView.findViewById(R.id.select_num)
        mCheckItemSelectAllBtn = mView.findViewById(R.id.checkbox_item_all)
        mNotFileFoundLayout = mView.findViewById(R.id.not_file_found_layout)
        mNotPermissionLayout = mView.findViewById(R.id.not_file_permission_layout)
        mCurrantFilePathTv = mView.findViewById(R.id.current_file_path)
        mFilesItemListView = mView.findViewById<ListView>(R.id.files_item_listview)


        mMoveBottomBtn = mBottomBar.findViewById(R.id.btn_move_bottom)
        mRenameBottomBtn = mBottomBar.findViewById(R.id.btn_rename_bottom)
        mCopyBottomBtn = mBottomBar.findViewById(R.id.btn_copy_bottom)
        mDeleteBottomBtn = mBottomBar.findViewById(R.id.btn_delete_bottom)
        mCancelBottomBtn = mBottomBar.findViewById(R.id.btn_cancel_bottom)

        mTitleText.setOnClickListener(this)
        mShareBtn.setOnClickListener(this)
        mDeleteBtn.setOnClickListener(this)
        mNewBtn.setOnClickListener(this)
        mCancelBtn.setOnClickListener(this)
        mQuitBtn.setOnClickListener(this)
        mEditBtn.setOnClickListener(this)
        mCheckItemSelectAllBtn.setOnClickListener(this)


        mMoveBottomBtn.setOnClickListener(this)
        mRenameBottomBtn.setOnClickListener(this)
        mCopyBottomBtn.setOnClickListener(this)
        mDeleteBottomBtn.setOnClickListener(this)
        mCancelBottomBtn.setOnClickListener(this)

        mView.findViewById<CheckBox>(R.id.checkbox_item_all).setOnClickListener(this)
        mView.findViewById<TextView>(R.id.go_to_setting_btn).setOnClickListener(this)
        mCancelBtn.visibility = View.GONE
        mQuitBtn.visibility = View.GONE
        mEditBtn.visibility = View.VISIBLE
        mNewBtn.visibility = View.VISIBLE

        mBaseViewModel.setNumber(0)
        mBaseViewModel.myInt.observe(viewLifecycleOwner, Observer {
            mSelectNumText.text = String.format(getString(R.string.select_0, switchNumber.toString()))
        })

    }

    private fun requestDataList() {
        println("yanglin start getData")
        if (mItemDataList.size == 0){
            WaitDialog.show("please wait..")
            Thread(Runnable {
//                val allFilesAndDirectories = FileUtil.getAllFilesAndDirectories(requireContext())
                val allFilesAndDirectories = FileUtil.getFileList(Environment.getExternalStorageDirectory())
                mItemDataList = FileUtil.fileListSort(allFilesAndDirectories)
                mFileDataBean.addAll(mItemDataList)
                requireActivity().runOnUiThread(Runnable {
                    setAdapter(mItemDataList)
                    WaitDialog.dismiss()
                })
            }).start()
        }else{
            if (mFilesItemLists.size < 1){
                setAdapter(mFileDataBean)
            }
        }
    }
    fun setAdapter(itemList: ArrayList<FileBean>){
        mItemDataList = itemList
        mItemCheckedArray = SparseBooleanArray()
        mFileAdapter = FilesItemViewAdapter(itemList, requireContext(), mItemCheckedArray)
        mFilesItemListView.adapter = mFileAdapter
        setOnListViewItemClickListener()
        mNotPermissionLayout.visibility = View.GONE
        if (HomeActivity.isPermission){
            if (itemList.size >0){
                mNotFileFoundLayout.visibility = View.GONE
                mFilesItemListView.visibility = View.VISIBLE
//                isEditShow(true)
            }else{
                mFilesItemListView.visibility = View.GONE
                mNotFileFoundLayout.visibility = View.VISIBLE
//                isEditShow(false)
            }

        }else{
            mNotPermissionLayout.visibility = View.VISIBLE
            mFilesItemListView.visibility = View.GONE
//            mNotFileFoundLayout.visibility = View.GONE
//            isEditShow(false)
        }
    }

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.btn_cancel ->{
                cancel()
            }
            R.id.btn_quit ->{
                backQuit()
            }
            R.id.btn_new ->{
                createNewDir()
            }
            R.id.btn_edit ->{
                mNewBtn.visibility = View.GONE
                mQuitBtn.visibility = View.GONE
                mEditBtn.visibility =View.GONE

                mCancelBtn.visibility = View.VISIBLE
                mShareBtn.visibility = View.VISIBLE
                mBottomBar.visibility = View.VISIBLE
                mSwitchSelectView.visibility = View.VISIBLE

                isClickEditBtn = true
                mFileAdapter?.setEditClickState(isClickEditBtn)
                HomeActivity.groupShow(!isClickEditBtn)
                mBaseViewModel.setNumber(switchNumber)
            }
            R.id.btn_delete ->{
                val customDialog = com.test.mydemo3.view.CustomDialog(requireContext())
                customDialog.setsCancel(View.OnClickListener {
                    customDialog.dismiss()
                }).setsConfirm(View.OnClickListener {
                    for (fileBean in mFileCheckedItemList!!){
                        mItemDataList.remove(fileBean)
                        MyApplication.mCleanSdk?.delete(File(fileBean.filePath))
                    }
                    mFileAdapter?.setData(mItemDataList)
                }).show()
                customDialog.isShowEditText(false)
                customDialog.setsTitle("Delete")
                customDialog.setsHint("Are you sure you want to delete ${mFileCheckedItemList.size} item?")

            }
            R.id.btn_share ->{
                if (switchNumber > 1){
                    var uris = ArrayList<Uri>()
                    for (fileBean: FileBean in mFileCheckedItemList){
                        uris.add(
                            FileProvider.getUriForFile(requireContext(),
                                context?.packageName + ".provider", File(fileBean.filePath)
                            )
                        )
                    }
                    shareMultipleFiles(uris)
                }else if (switchNumber == 1){
                    val uri = Uri.parse(mFileCheckedItemList[0].filePath)
                    shareFile(uri)
                }
            }
            R.id.btn_move_bottom ->{
                if (switchNumber == 0) return
//                mFileAdapter?.setEditClickState(false)
                isMove = true
                var intent = Intent(context, MoveOrCopyActivity::class.java)
                intent.putExtra("checkedItemBeans", mFileCheckedItemList)
                intent.putExtra("operate", "move")
                startActivity(intent)
                switchNumber = 0
                mItemCheckedArray.clear()
                mFileCheckedItemList.clear()

            }
            R.id.btn_rename_bottom ->{
                isRename = true
                rename()
            }
            R.id.btn_copy_bottom ->{
                if (switchNumber == 0) return
                isCopy = true
                var intent = Intent(context, MoveOrCopyActivity::class.java)
                intent.putExtra("checkedItemBeans", mFileCheckedItemList)
                intent.putExtra("operate", "copy")
                context?.startActivity(intent)
                switchNumber = 0
                mItemCheckedArray.clear()
                mFileCheckedItemList.clear()

            }
            R.id.btn_delete_bottom ->{
                val files = ArrayList<String>()
                for (fileBean: FileBean in mFileCheckedItemList){
                    files.add(fileBean.filePath)
                }
                if(FileUtil.deleteFiles(files)){
                    Toast.makeText(context, "delete success!", Toast.LENGTH_LONG).show()
                    cancel()
                    mItemDataList.clear()
                    mFileDataBean.clear()
                    requestDataList()
                }else{
                    Toast.makeText(context, "delete failed!", Toast.LENGTH_LONG).show()
                }
            }
            R.id.btn_cancel_bottom ->{

                mTitleText.text = mTitleStr
                mCancelBottomBtn.visibility = View.GONE
                mQuitBtn.visibility = View.GONE
                mCancelBtn.visibility = View.VISIBLE
//                mDeleteBtn.visibility = View.VISIBLE
                mShareBtn.visibility = View.VISIBLE
                mCopyBottomBtn.visibility = View.VISIBLE
                mMoveBottomBtn.visibility = View.VISIBLE
                mRenameBottomBtn.visibility = View.VISIBLE
                mDeleteBottomBtn.visibility = View.VISIBLE
            }
            R.id.checkbox_item_all ->{
                isClickCheckBoxAllBtn = !isClickCheckBoxAllBtn
                mCheckItemSelectAllBtn.isChecked = isClickCheckBoxAllBtn
                selectAll()
            }
            R.id.go_to_setting_btn ->{
                PermissionUtil.requestPermission(context)
            }
        }
    }

    fun cancel(){
        setStateCheckedMap(false)
        mNewBtn.visibility = View.VISIBLE
        mQuitBtn.visibility = View.VISIBLE
        mEditBtn.visibility =View.VISIBLE
        mCancelBtn.visibility = View.GONE
        mDeleteBtn.visibility = View.GONE
        mShareBtn.visibility = View.GONE
        mBottomBar.visibility = View.GONE
        mSwitchSelectView.visibility = View.GONE
        if (mFilesItemLists.size == 0){
            mQuitBtn.visibility = View.GONE
        }

        isClickEditBtn = false
        mFileAdapter?.setEditClickState(isClickEditBtn)
        HomeActivity.groupShow(!isClickEditBtn)
        switchNumber = 0
        if (mFileAdapter != null){
            mFileAdapter?.notifyDataSetChanged()
        }
    }
    fun backQuit(): Boolean{
        val size = mFilesItemLists.size
        if (size-1 == 0){
            mQuitBtn.visibility = View.GONE
            mCurrantFilePathTv.text = "Internal Storage/"
        }
        if (size < 1){
            if (mNotFileFoundLayout.isVisible && mItemDataList.size > 0){
                mFilesItemListView.visibility = View.VISIBLE
                mNotFileFoundLayout.visibility = View.GONE
                mFileAdapter?.setData(mItemDataList)
                return false
            }
            return true
        }else{
            mFileAdapter?.setData(mFilesItemLists[size-1])
            mItemDataList = mFilesItemLists[size-1]
            mFilesItemListView.visibility = View.VISIBLE
            mNotFileFoundLayout.visibility = View.GONE
            mFilesItemLists.remove(mFilesItemLists[size-1])
            mCurrentList.remove(mCurrentList[size-1])
            if (size - 1 > 0){
                mCurrentFileBean = mCurrentList[size-2]
                mCurrantFilePathTv.text = "Internal Storage/ ${mCurrentFileBean?.fileName}"
            }else{
                mCurrantFilePathTv.text = "Internal Storage/"
            }
            return false
        }
    }
    private fun shareFile(uri: Uri) {
        val intent = Intent(Intent.ACTION_SEND)
        intent.type = "text/plain"
        intent.putExtra(Intent.EXTRA_STREAM, uri)
        startActivity(Intent.createChooser(intent, "Share File"))
    }
    private fun shareMultipleFiles(uris: ArrayList<Uri>) {
        val intent = Intent(Intent.ACTION_SEND_MULTIPLE)
        intent.type = "*/*"
        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris)
        startActivity(Intent.createChooser(intent, "Share Files"))
    }
    fun selectAll(){
        mFileCheckedItemList.clear()
        switchNumber = if (isClickCheckBoxAllBtn){
            setStateCheckedMap( true)
            mFileCheckedItemList.addAll(mItemDataList)
            mFileCheckedItemList.size
        }else{
            setStateCheckedMap( false)
            0
        }
        mFileAdapter?.notifyDataSetChanged()
        mBaseViewModel.setNumber(switchNumber)
//        mSelectNumText.text = String.format(getString(R.string.select_0, mSelectNum.toString()))
    }
    fun updateCheckBoxStatus(view: View, position: Int){
        val viewHolder = view.tag as FilesItemViewAdapter.ViewHolder
        viewHolder.selectSwitch.toggle()
        mFilesItemListView.setItemChecked(position, viewHolder.selectSwitch.isChecked)
        mItemCheckedArray.put(position, viewHolder.selectSwitch.isChecked)
        if (viewHolder.selectSwitch.isChecked){
            mFileCheckedItemList.add(mItemDataList[position])
        }else{
            mFileCheckedItemList.remove(mItemDataList[position])
        }
        mFileAdapter?.notifyDataSetChanged()
        switchNumber = mFileCheckedItemList.size
        mBaseViewModel.setNumber(switchNumber)
    }
    fun setStateCheckedMap(isChecked: Boolean){
        for(i in mItemDataList.indices){
            mItemCheckedArray.put(i, isChecked)
            mFilesItemListView.setItemChecked(i, isChecked)
        }
    }

    private fun rename() {
        if (BaseActivity.switchNumber == 0 || BaseActivity.switchNumber > 1) return
        val customDialog = CustomDialog(context)
        customDialog.setsConfirm(View.OnClickListener {
            val name = customDialog.getEditTextStr()
            Log.e(
                "yanglin ",
                "onClick: rename = $name checkedPath =${mFileCheckedItemList[0].filePath}",
            )
            val renameFile = FileUtil.renameFile(
                mFileCheckedItemList[0].filePath,
                name + ".${mFileCheckedItemList[0].fileType}"
            )
            if (renameFile) {
                Toast.makeText(context, "new fileName success!", Toast.LENGTH_LONG).show()
                for (fileBean: FileBean in mItemDataList) {
                    if (fileBean.fileName.contains(mFileCheckedItemList[0].fileName)
                        && fileBean.filePath.contains(mFileCheckedItemList[0].filePath)
                    ) {
                        fileBean.fileName = name + ".${mFileCheckedItemList[0].fileType}"
                    }
                }
            } else {
                Toast.makeText(context, "new fileName failed!", Toast.LENGTH_LONG).show()
            }
            customDialog.dismiss()
        }).setsCancel(View.OnClickListener {
            customDialog.dismiss()
        }).show()
        customDialog.setsTitle("Rename")
        customDialog.setsHint("Please enter a new name")
        switchNumber = 0
    }

    private fun createNewDir() {
        val customDialog = CustomDialog(context)

        customDialog.setsCancel(View.OnClickListener {
            customDialog.dismiss()
        }).setsConfirm(View.OnClickListener {
            val editTextStr = customDialog.getEditTextStr()
            for (fileBean: FileBean in mItemDataList) {
                if (editTextStr.equals(fileBean.fileName)) {
                    Toast.makeText(context, "Existing file", Toast.LENGTH_SHORT).show()
                    customDialog.dismiss()
                    return@OnClickListener
                }
            }
            val filesItemBean = FileUtil.createDirectory(mCurrentFilePath, editTextStr)
            if (filesItemBean.filePath.equals("-1")) {
                Toast.makeText(context, "Create failed", Toast.LENGTH_SHORT).show()
                customDialog.dismiss()
            } else {
                if (filesItemBean.childList.size == 0){
                    mFilesItemListView.visibility = View.VISIBLE
                    mNotFileFoundLayout.visibility = View.GONE
                    mItemDataList.clear()
                }
//                mItemDataList.add(filesItemBean)
                mFileDataBean.add(filesItemBean)
                mFileAdapter?.setData(mFileDataBean)
                mFileAdapter?.notifyDataSetChanged()
                customDialog.dismiss()
            }
        }).show()
    }

    fun setOnListViewItemClickListener(){
        mFilesItemListView.setOnItemClickListener { parent, view, position, id ->
            Log.e("TAG", "setOnListViewItemClickListener: 第$position" )
            if (!isClickEditBtn){
                mQuitBtn.visibility = View.VISIBLE
                mCurrentFileBean = mItemDataList[position]
                if (!mCurrentFileBean?.fileType.equals("dir")){
                    return@setOnItemClickListener
                }
                mCurrantFilePathTv.text = "Internal Storage/ ${mCurrentFileBean?.fileName}"
                mCurrentList.add(mCurrentFileBean!!)
                mFilesItemLists.add(mItemDataList)
                if (mCurrentFileBean?.fileType.equals("dir") && mCurrentFileBean?.childList?.size!! > 0){
                    Thread(Runnable {
                        requireActivity().runOnUiThread {
                            mItemDataList = FileUtil.getFileList(File(mCurrentFileBean!!.filePath))
//                            mItemDataList = mCurrentFileBean!!.childList
                            val fileListSort = FileUtil.fileListSort(mItemDataList)
                            mFileAdapter?.setData(fileListSort)
                        }
                    }).start()
                }else if(mCurrentFileBean?.fileType.equals("dir") && mCurrentFileBean?.childList?.size == 0){
//                    mFilesItemListView.visibility = View.GONE
                    mNotFileFoundLayout.visibility = View.VISIBLE
                }

            }else{
                updateCheckBoxStatus(view, position)
            }
        }
    }
    override fun onResume() {
        super.onResume()
        if (mFileAdapter != null && (isCopy || isMove)){
            cancel()
            cancel()
            mFileDataBean.clear()
            mFileAdapter?.setEditClickState(false)
            val allFilesAndDirectories = FileUtil.getFileList(Environment.getExternalStorageDirectory())
            mItemDataList = FileUtil.fileListSort(allFilesAndDirectories)
            mFileDataBean.addAll(mItemDataList)
            mFileAdapter?.setData(mItemDataList)
            mFileAdapter?.setEditClickState(false)
            mFileAdapter?.notifyDataSetChanged()
            isMove = false
            isCopy = false
        }
        if (PermissionUtil.checkGrantedPermission(requireActivity())){
            requestDataList()
        }else {
            mNotPermissionLayout.visibility = View.VISIBLE
        }
    }

}