package com.xm.test.myfilemaster.base

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.util.SparseBooleanArray
import android.view.View
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.xm.test.myfilemaster.MyApplication
import com.xm.test.myfilemaster.R
import com.xm.test.myfilemaster.activity.BaseActivityViewModel
import com.xm.test.myfilemaster.activity.HomeActivity
import com.xm.test.myfilemaster.activity.MoveOrCopyActivity
import com.xm.test.myfilemaster.adapter.FilesItemViewAdapter
import com.xm.test.myfilemaster.model.FileBean
import com.xm.test.myfilemaster.util.FileUtil
import com.xm.test.myfilemaster.util.PermissionUtil
import com.xm.test.myfilemaster.view.CustomDialog
import java.io.File

abstract class BaseActivity : BaseAbsView(), BaseActivityListener{
    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 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 mBinding: Binding

    lateinit var mBaseViewModel : BaseActivityViewModel

    var mIsMove = true //true is move, false is copy,
    lateinit var mFileAdapter: FilesItemViewAdapter
    lateinit var mItemCheckedArray: SparseBooleanArray
    var mFileCheckedItemList = ArrayList<FileBean>()
    lateinit var mItemDataList: ArrayList<FileBean>
    var mFilesItemLists = ArrayList<ArrayList<FileBean>>()
    var mCurrentFilePath: String = FileUtil.EXTERNAL_STORAGE
    var mCurrentFileBean: FileBean? = null
    var mTitleStr: String = ""
    var mCurrentList: ArrayList<FileBean> = ArrayList()
    lateinit var mCurrantFilePathTv: TextView

    companion object{
        var isClickEditBtn = false
        var isClickCheckBoxAllBtn = false
        var switchNumber = 0
    }

    abstract fun getLayout():Int

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        isQuitShow(true)
        isNewShow(true)
        isEditShow(true)
    }

    override fun initView() {
        setContentView(getLayout())

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

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


        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)

        findViewById<CheckBox>(R.id.checkbox_item_all).setOnClickListener(this)
        findViewById<TextView>(R.id.go_to_setting_btn).setOnClickListener(this)

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

    override fun setTitle(str: String) {
        mTitleStr = str
        mTitleText.text=mTitleStr
    }

    override fun isDeleteShow(isShow: Boolean) {
        mDeleteBtn.visibility = if (isShow) View.VISIBLE else View.GONE
    }

    override fun isShareShow(isShow: Boolean) {
        mShareBtn.visibility = if (isShow) View.VISIBLE else View.GONE
    }

    override fun isNewShow(isShow: Boolean) {
        mNewBtn.visibility = if (isShow) View.VISIBLE else View.GONE
    }

    override fun isCancelShow(isShow: Boolean) {
        mCancelBtn.visibility = if (isShow) View.VISIBLE else View.GONE
    }

    override fun isQuitShow(isShow: Boolean) {
        mQuitBtn.visibility = if (isShow) View.VISIBLE else View.GONE
    }

    override fun isEditShow(isShow: Boolean) {
        mEditBtn.visibility = if (isShow) View.VISIBLE else View.GONE
    }
    fun isCurrantTvShow(isShow: Boolean){
        mCurrantFilePathTv.visibility = if (isShow) View.VISIBLE else View.GONE
    }

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.btn_cancel ->{
                cancel()
            }
            R.id.btn_quit ->{
                if (backQuit()) finish()
            }
            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)
            }
            R.id.btn_delete ->{

                val customDialog = CustomDialog(this)
                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?")
                customDialog.setsRightDelete("Delete")
            }
            R.id.btn_share ->{
                if (switchNumber > 1){
                    var uris = ArrayList<Uri>()
                    for (fileBean: FileBean in mFileCheckedItemList){
                        uris.add(
                            FileProvider.getUriForFile(this,
                                this.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
//                mCancelBottomBtn.visibility = View.VISIBLE
//                mQuitBtn.visibility = View.VISIBLE
//                mCancelBtn.visibility = View.GONE
////                mDeleteBtn.visibility = View.GONE
//                mShareBtn.visibility = View.GONE
//                mCopyBottomBtn.visibility = View.GONE
//                mRenameBottomBtn.visibility = View.GONE
//                mDeleteBottomBtn.visibility = View.GONE
//                mTitleText.text = "Move To.."
//                if (mFilesItemLists.size>0){
//                    intent.putExtra("fileBeans",mFilesItemLists[0])
//                }else{
//                    intent.putExtra("fileBeans",mItemDataList)
//                }
//                intent.putExtra("filePath", mFileCheckedItemList[0].filePath)
                var intent = Intent(this, MoveOrCopyActivity::class.java)
                intent.putExtra("checkedItemBeans", mFileCheckedItemList)
                intent.putExtra("operate", "move")
                startActivity(intent)

            }
            R.id.btn_rename_bottom ->{
                rename()
            }
            R.id.btn_copy_bottom ->{
                if (switchNumber == 0) return
//                mCancelBottomBtn.visibility = View.VISIBLE
//                mQuitBtn.visibility = View.VISIBLE
//                mCancelBtn.visibility = View.GONE
//                mDeleteBtn.visibility = View.GONE
//                mShareBtn.visibility = View.GONE
//                mMoveBottomBtn.visibility = View.GONE
//                mRenameBottomBtn.visibility = View.GONE
//                mDeleteBottomBtn.visibility = View.GONE
//                mTitleText.text = "Copy To.."
                var intent = Intent(this, MoveOrCopyActivity::class.java)
                intent.putExtra("checkedItemBeans", mFileCheckedItemList)
                intent.putExtra("operate", "copy")
                startActivity(intent)

            }
            R.id.btn_delete_bottom ->{
                val files = ArrayList<String>()
                for (fileBean: FileBean in mFileCheckedItemList){
                    files.add(fileBean.filePath)
                }
                if(FileUtil.deleteFiles(files)){
                    Toast.makeText(this, "delete success!", Toast.LENGTH_LONG).show()
                }else{
                    Toast.makeText(this, "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(this)
//                Toast.makeText(this, "你好", Toast.LENGTH_LONG).show()
//                Intent().apply { action = Intent.ACTION_APPLICATION_DETAILS_SETTINGS }
            }
        }
    }

    private fun rename() {
        if (switchNumber == 0 || switchNumber > 1) return
        val customDialog = CustomDialog(this)
        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(this, "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(this, "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")
    }

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

        customDialog.setsCancel(View.OnClickListener {
            customDialog.dismiss()
        }).setsConfirm(View.OnClickListener {
            val editTextStr = customDialog.getEditTextStr()

            mItemDataList
            for (fileBean: FileBean in mItemDataList) {
                if (editTextStr.equals(fileBean.fileName)) {
                    Toast.makeText(this, "Existing file", Toast.LENGTH_SHORT).show()
                    customDialog.dismiss()
                    return@OnClickListener
                }
            }
            val filesItemBean = FileUtil.createDirectory(mCurrentFilePath, editTextStr)
            if (filesItemBean.filePath.equals("-1")) {
                Toast.makeText(this, "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)
                mFileAdapter.setData(mItemDataList)
                mFileAdapter.notifyDataSetChanged()
                customDialog.dismiss()
            }
        }).show()
    }

    fun setStateCheckedMap(isChecked: Boolean){
        for(i in mItemDataList.indices){
            mItemCheckedArray.put(i, isChecked)
            mFilesItemListView.setItemChecked(i, isChecked)
        }
    }

    fun setOnListViewItemClickListener(lv: ListView){
        lv.setOnItemClickListener { parent, view, position, id ->
            Log.e("TAG", "setOnListViewItemClickListener: 第$position" )
            if (!isClickEditBtn){
                mCurrentFileBean = mItemDataList[position]
                if (!mCurrentFileBean?.fileType.equals("dir")){
                    return@setOnItemClickListener
                }
                mFilesItemLists.add(mItemDataList)
                mCurrantFilePathTv.text = "Internal Storage/ ${mCurrentFileBean?.fileName}"
                mCurrentList.add(mCurrentFileBean!!)
                if (mCurrentFileBean?.fileType.equals("dir") && mCurrentFileBean?.childList?.size!! > 0){
                    Thread(Runnable {
                        runOnUiThread {
                            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)
            }
        }
    }

    fun setAdapter(lv: ListView, itemList: ArrayList<FileBean>){
        mFilesItemListView = lv
        mItemDataList = itemList
        mItemCheckedArray = SparseBooleanArray()
        mFileAdapter = FilesItemViewAdapter(itemList, this, mItemCheckedArray)
        mFilesItemListView.adapter = mFileAdapter
        setOnListViewItemClickListener(mFilesItemListView)
        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)
        }
    }

    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 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 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

        isClickEditBtn = false
        mFileAdapter.setEditClickState(isClickEditBtn)
        switchNumber = 0
        if (mFileAdapter != null){
            mFileAdapter.notifyDataSetChanged()
        }
    }

    override fun onBackPressed() {
        if (isClickEditBtn){
            cancel()
        }else{
            if (backQuit()) super.onBackPressed()
        }
    }
    fun backQuit(): Boolean{
        val size = mFilesItemLists.size
        if (size-1 == 0){
            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 getCurrentFileBean() : FileBean?{
        return mCurrentFileBean
    }

    fun setOnClickBtn() {
        mEditBtn.setOnClickListener {
            mBottomBar.visibility = View.GONE
            mEditBtn.visibility = View.GONE
            mQuitBtn.visibility = View.GONE
            findViewById<ImageView>(R.id.btn_share).visibility = View.GONE
            findViewById<View>(R.id.switch_and_select_layout).visibility = View.VISIBLE
            mDeleteBtn.visibility = View.VISIBLE
            mCancelBtn.visibility = View.VISIBLE
            BaseActivity.isClickEditBtn = true
            isNewShow(false)
            mFileAdapter.setEditClickState(true)

        }
        mCancelBtn.setOnClickListener {
            mEditBtn.visibility = View.VISIBLE
            mQuitBtn.visibility = View.VISIBLE
            mDeleteBtn.visibility = View.GONE
            mCancelBtn.visibility = View.GONE
            findViewById<View>(R.id.switch_and_select_layout).visibility = View.GONE
            BaseActivity.isClickEditBtn = false
            isNewShow(false)
            mFileAdapter.setEditClickState(false)
        }
//        mDeleteBtn.setOnClickListener {
//            super.onClick(mDeleteBtn)
//        }
    }
    fun setFileShow(isShow: Boolean){
        mFileAdapter.setFileShow(isShow)
    }

}