package org.mosad.teapod.util

import android.content.Intent
import android.view.View
import android.view.Window
import android.widget.TextView
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.fragment.app.Fragment
import org.mosad.teapod.R
import org.mosad.teapod.parser.crunchyroll.Collection
import org.mosad.teapod.parser.crunchyroll.Collection2
import org.mosad.teapod.parser.crunchyroll.Item
import org.mosad.teapod.parser.crunchyroll.PlayheadObject
import org.mosad.teapod.ui.activity.player.PlayerActivity
import java.util.*

/**
 * Create a Intent for PlayerActivity with season and episode id.
 *
 * @param seasonId The ID of the season the episode to be played is in
 * @param episodeId The ID of the episode to play
 */
fun Fragment.playerIntent(seasonId: String, episodeId: String) = Intent(context, PlayerActivity::class.java).apply {
    putExtra(getString(R.string.intent_season_id), seasonId)
    putExtra(getString(R.string.intent_episode_id), episodeId)
}

fun TextView.setDrawableTop(drawable: Int) {
    this.setCompoundDrawablesWithIntrinsicBounds(0, drawable, 0, 0)
}

fun <T> concatenate(vararg lists: List<T>): List<T> {
    return listOf(*lists).flatten()
}

// TODO move to correct location
fun Collection<Item>.toItemMediaList(): List<ItemMedia> {
    return this.items.map {
        ItemMedia(it.id, it.title, it.images.poster_wide[0][0].source)
    }
}

@JvmName("toItemMediaListItem")
fun List<Item>.toItemMediaList(): List<ItemMedia> {
    return this.map {
        ItemMedia(it.id, it.title, it.images.poster_wide[0][0].source)
    }
}

fun Locale.toDisplayString(fallback: String): String {
    return if (this.displayLanguage.isNotEmpty() && this.displayCountry.isNotEmpty()) {
        "${this.displayLanguage} (${this.displayCountry})"
    } else if (this.displayCountry.isNotEmpty()) {
        this.displayLanguage
    } else {
        fallback
    }
}

fun Collection2<PlayheadObject>.toPlayheadsMap(): Map<String, PlayheadObject> {
    return this.data.associateBy { it.contentId }
}

fun hideBars(window: Window?, root: View) {
    if (window != null) {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        WindowInsetsControllerCompat(window, root).let { controller ->
            controller.hide(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.navigationBars())
            controller.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        }
    }
}
