package com.github.libretube.ui.dialogs

import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.fragment.app.DialogFragment
import com.github.libretube.R
import com.github.libretube.constants.IntentData
import com.github.libretube.databinding.DialogDownloadPlaylistBinding
import com.github.libretube.enums.PlaylistType
import com.github.libretube.extensions.serializable
import com.github.libretube.services.PlaylistDownloadEnqueueService
import com.github.libretube.util.TextUtils
import com.google.android.material.dialog.MaterialAlertDialogBuilder

/** Simple Audio / Video chooser for complete playlist downloads. */
class DownloadPlaylistDialog : DialogFragment() {
    private lateinit var playlistId: String
    private lateinit var playlistName: String
    private lateinit var playlistType: PlaylistType

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        playlistId = requireArguments().getString(IntentData.playlistId)!!
        playlistName = requireArguments().getString(IntentData.playlistName)
            ?: TextUtils.getFileSafeTimeStampNow()
        playlistType = requireArguments().serializable(IntentData.playlistType)!!
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val binding = DialogDownloadPlaylistBinding.inflate(layoutInflater)
        binding.playlistTitle.text = playlistName

        binding.downloadAudioButton.setOnClickListener {
            enqueuePlaylist(downloadVideo = false)
        }
        binding.downloadVideoButton.setOnClickListener {
            enqueuePlaylist(downloadVideo = true)
        }

        return MaterialAlertDialogBuilder(requireContext())
            .setTitle(R.string.download_playlist)
            .setView(binding.root)
            .setNegativeButton(R.string.cancel, null)
            .create()
    }

    private fun enqueuePlaylist(downloadVideo: Boolean) {
        // A tiny positive max value intentionally makes the enqueue service choose the lowest
        // available quality for each video/audio track in the playlist.
        val compactQualitySentinel = 1

        val downloadEnqueueIntent = Intent(requireContext(), PlaylistDownloadEnqueueService::class.java)
            .putExtra(IntentData.playlistId, playlistId)
            .putExtra(IntentData.playlistType, playlistType)
            .putExtra(IntentData.playlistName, playlistName)
            .putExtra(
                IntentData.maxVideoQuality,
                if (downloadVideo) compactQualitySentinel else 0
            )
            .putExtra(IntentData.maxAudioQuality, compactQualitySentinel)

        ContextCompat.startForegroundService(requireContext(), downloadEnqueueIntent)
        dismiss()
    }
}
