/*
 * Lunar Launcher
 * Copyright (C) 2022 Md Rasel Hossain
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package bums.lunatic.launcher.settings.childs

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import bums.lunatic.launcher.R
import bums.lunatic.launcher.databinding.SettingsAppsBinding
import bums.lunatic.launcher.helpers.PrefHelper
import bums.lunatic.launcher.helpers.PrefKey
import bums.lunatic.launcher.helpers.PrefLong
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.slider.Slider
import kotlin.system.exitProcess


internal class Apps : BottomSheetDialogFragment() {

    private lateinit var binding: SettingsAppsBinding
    private var settingsChanged: Boolean = false
    private var packageManager: PackageManager? = null

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val bottomSheetView = View.inflate(context, R.layout.settings_apps, null)
        val dialog = super.onCreateDialog(savedInstanceState).apply {
            setContentView(bottomSheetView)
        }

        // Set the height to wrap_content
        BottomSheetBehavior.from(bottomSheetView.parent as View)
            .peekHeight = resources.displayMetrics.heightPixels // Adjust this if needed

        return dialog
    }

    @SuppressLint("RtlHardcoded")
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        binding = SettingsAppsBinding.inflate(inflater, container, false)
        packageManager = requireActivity().packageManager


        binding.keyboardAutoGroup.isChecked = PrefHelper.openWithKayboard
        binding.keyboardAutoGroup.setOnCheckedChangeListener { c,v ->
            settingsChanged = true
            PrefHelper.openWithKayboard = v
        }

        binding.quickLaunchGroup.isChecked = PrefHelper.useQuickLaunch
        binding.quickLaunchGroup.setOnCheckedChangeListener { c,v ->
            settingsChanged = true
            PrefHelper.useQuickLaunch = v
        }

        binding.appsCountGroup.isChecked = PrefHelper.showAppResultCount
        binding.appsCountGroup.setOnCheckedChangeListener { c,v ->
            settingsChanged = true
            PrefHelper.showAppResultCount = v
        }


        ((PrefKey.maxQueryCount.get(18L) as? Long)?.toFloat() ?: 18F).let {
            binding.columnsCountTitle.text = getString(R.string.grid_columns_count) +" [${it.toInt()}]"
            binding.columnsCount.value = it
        }

        PrefLong.shortTimePeriod.get(20L).let {
            binding.shortTimeTitle.text = getString(R.string.shortTimeTitle) +" [${it.toInt()}분 마다]"
            binding.shortTime.value = it.toFloat()
        }
        PrefLong.midTimePeriod.get(30L).let {
            binding.middleTimeTitle.text = getString(R.string.middleTimeTitle) +" [${it.toInt()}분 마다]"
            binding.middleTime.value = it.toFloat()
        }

        PrefLong.longTimePeriod.get(60L).let {
            binding.longTimeTitle.text = getString(R.string.longTimeTitle) +" [${it.toInt()}분 마다]"
            binding.longTime.value = it.toFloat()
        }

        PrefLong.locationTimePeriod.get(20L).let {
            binding.locationTimeTitle.text = getString(R.string.locationTimeTitle) +" [${it.toInt()}분 마다]"
            binding.locationTime.value = it.toFloat()
        }

        PrefLong.locationDistance.get(200L).let {
            binding.locationDistanceTitle.text = getString(R.string.locationDistanceTitle) +" [${it.toInt()}분 마다]"
            binding.locationDistance.value = it.toFloat()
        }

//        binding.scrollbarHeight.value = settingsPrefs!!.getInt(KEY_SCROLLBAR_HEIGHT, DEFAULT_SCROLLBAR_HEIGHT).toFloat()

        return binding.root
    }

    @SuppressLint("RtlHardcoded")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        (requireDialog() as BottomSheetDialog).dismissWithAnimation = true


        binding.columnsCount.addOnChangeListener(Slider.OnChangeListener { _, value, _ ->
            settingsChanged = true
            PrefKey.maxQueryCount.set(value.toLong())
            binding.columnsCountTitle.text = getString(R.string.grid_columns_count) +" [${value.toInt()}]"
        })

        binding.shortTime.addOnChangeListener(Slider.OnChangeListener { _, value, _ ->
            settingsChanged = true
            PrefKey.shortTimePeriod.set(value.toLong())
            binding.shortTimeTitle.text = getString(R.string.shortTimeTitle) +" [${value.toInt()}분 마다]"
        })
        binding.middleTime.addOnChangeListener(Slider.OnChangeListener { _, value, _ ->
            settingsChanged = true
            PrefKey.midTimePeriod.set(value.toLong())
            binding.middleTimeTitle.text = getString(R.string.middleTimeTitle) +" [${value.toInt()}분 마다]"
        })
        binding.longTime.addOnChangeListener(Slider.OnChangeListener { _, value, _ ->
            settingsChanged = true
            PrefKey.longTimePeriod.set(value.toLong())
            binding.longTimeTitle.text = getString(R.string.longTimeTitle) +" [${value.toInt()}]분 마다]"
        })

        binding.locationDistance.addOnChangeListener(Slider.OnChangeListener { _, value, _ ->
            settingsChanged = true
            PrefLong.locationDistance.set(value.toLong())
            binding.locationDistanceTitle.text = getString(R.string.locationDistanceTitle) +" [${value.toInt()}]미터 마다]"
        })
        binding.locationTime.addOnChangeListener(Slider.OnChangeListener { _, value, _ ->
            settingsChanged = true
            PrefLong.locationTimePeriod.set(value.toLong())
            binding.locationTimeTitle.text = getString(R.string.locationTimeTitle) +" [${value.toInt()}]분 마다]"
        })

    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (settingsChanged) {
            MaterialAlertDialogBuilder(requireActivity())
                .setTitle(R.string.restart_now)
                .setMessage(R.string.restart_message)
                .setPositiveButton(R.string.restart) { _, _ ->
                    exitProcess(0)
                }
                .setNeutralButton(R.string.later, null)
                .show()
        }
    }

}
