package org.mosad.teapod.ui.activity.player.fragment

import android.content.DialogInterface
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.util.TypedValue
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.children
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import org.mosad.teapod.R
import org.mosad.teapod.databinding.PlayerLanguageSettingsBinding
import org.mosad.teapod.ui.activity.player.PlayerViewModel
import org.mosad.teapod.util.hideBars
import java.util.*

class LanguageSettingsDialogFragment : DialogFragment() {

    private lateinit var model: PlayerViewModel
    private lateinit var binding: PlayerLanguageSettingsBinding

    private var selectedSubtitleLocale = Locale.ROOT
    private var selectedAudioLocale = Locale.ROOT

    companion object {
        const val TAG = "LanguageSettingsDialogFragment"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, R.style.FullScreenDialogStyle)
        model = ViewModelProvider(requireActivity())[PlayerViewModel::class.java]
        selectedSubtitleLocale = model.currentSubtitleLocale
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        binding = PlayerLanguageSettingsBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        var selectedSubtitleView: TextView? = null
        model.currentStreams.data[0].adaptive_hls.keys.forEach { languageTag ->
            val locale = Locale.forLanguageTag(languageTag)
            val subtitleView = addLanguage(binding.linearSubtitleLanguages, locale) { v ->
                selectedSubtitleLocale = locale
                updateSelectedLanguage(binding.linearSubtitleLanguages, v as TextView)
            }

            // if the view is the currently selected one, highlight it
            if (locale == model.currentSubtitleLocale) {
                selectedSubtitleView = subtitleView
                updateSelectedLanguage(binding.linearSubtitleLanguages, subtitleView)
            }
        }

        val currentAudioLocal = Locale.forLanguageTag(model.currentVersion.audioLocale)
        var selectedAudioView: TextView? = null
        model.currentEpisode.versions?.forEach { version ->
            val locale = Locale.forLanguageTag(version.audioLocale)
            val audioView = addLanguage(binding.linearAudioLanguages, locale) { v ->
                selectedAudioLocale = locale
                updateSelectedLanguage(binding.linearAudioLanguages, v as TextView)
            }

            // if the view is the currently selected one, highlight it
            if (locale == currentAudioLocal) {
                selectedAudioView = audioView
                updateSelectedLanguage(binding.linearAudioLanguages, audioView)
            }
        }

        binding.buttonCloseLanguageSettings.setOnClickListener { dismiss() }
        binding.buttonCancel.setOnClickListener { dismiss() }
        binding.buttonSelect.setOnClickListener {
            model.setLanguage(selectedAudioLocale, selectedSubtitleLocale)
            dismiss()
        }

        // initially hide the status and navigation bar
        hideBars(requireDialog().window, binding.root)

        // scroll to the position of the view, if it's the selected language
        binding.scrollSubtitleLanguages.post {
            binding.scrollSubtitleLanguages.scrollTo(0, selectedSubtitleView?.top ?: 0)
        }

        binding.scrollAudioLanguages.post {
            binding.scrollSubtitleLanguages.scrollTo(0, selectedAudioView?.top ?: 0)
        }
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        model.player.play()
    }

    private fun addLanguage(linear: LinearLayout, locale: Locale, onClick: View.OnClickListener): TextView {
        val text = TextView(context).apply {
            height = 96
            gravity = Gravity.CENTER_VERTICAL
            text = if (locale == Locale.ROOT) context.getString(R.string.no_subtitles) else locale.displayLanguage
            setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
            setTextColor(context.resources.getColor(R.color.player_text, context.theme))
            setPadding(75, 0, 0, 0)

            setOnClickListener(onClick)
        }

        linear.addView(text)

        return text
    }

    /**
     * Highlights the selected audio/subtitle language
     *
     * @param languageLayout The audio/subtitle Layout to update
     * @param selected The newly selected language TextView
     */
    private fun updateSelectedLanguage(languageLayout: LinearLayout, selected: TextView) {
        // rest all tf to not selected style
        languageLayout.children.forEach { child ->
            if (child is TextView) {
                child.apply {
                    setTextColor(context.resources.getColor(R.color.player_text, context.theme))
                    setTypeface(null, Typeface.NORMAL)
                    setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, 0, 0)
                    setPadding(75, 0, 0, 0)
                }
            }
        }

        // set selected to selected style
        selected.apply {
            setTextColor(context.resources.getColor(R.color.player_white, context.theme))
            setTypeface(null, Typeface.BOLD)
            setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_baseline_check_24, 0, 0, 0)
            setPadding(0, 0, 0, 0)
            compoundDrawablesRelative.getOrNull(0)?.setTint(Color.WHITE)
            compoundDrawablePadding = 12
        }
    }
}
