package com.player.musicoo.innertube.requests

import com.player.musicoo.innertube.Innertube
import com.player.musicoo.innertube.models.BrowseResponse
import com.player.musicoo.innertube.models.ContinuationResponse
import com.player.musicoo.innertube.models.MusicShelfRenderer
import com.player.musicoo.innertube.models.SearchResponse
import com.player.musicoo.innertube.models.SectionListRenderer
import com.player.musicoo.innertube.models.bodies.BrowseBody
import com.player.musicoo.innertube.models.bodies.ContinuationBody
import com.player.musicoo.innertube.models.bodies.SearchBody
import com.player.musicoo.innertube.utils.runCatchingNonCancellable
import com.player.musicoo.util.LogTag
import io.ktor.client.call.body
import io.ktor.client.request.post
import io.ktor.client.request.setBody

suspend fun Innertube.moSearchPage(body: SearchBody): Result<List<Innertube.SearchDataPage>>? =
    runCatchingNonCancellable {

        val response = client.post(search) {
            setBody(body)
        }.body<SearchResponse>()

        val searchDataPageList: MutableList<Innertube.SearchDataPage> = mutableListOf()

        val contents = response.contents
            ?.tabbedSearchResultsRenderer
            ?.tabs
            ?.firstOrNull()
            ?.tabRenderer
            ?.content
            ?.sectionListRenderer
            ?.contents
        var type = -1
        var title = ""
        var query = ""
        var params = ""
        var continuation = ""
        if (contents != null) {
            for (content: SectionListRenderer.Content in contents) {
                //保证每次循环都是一个新的集合
                val searchResultItemList: MutableList<Innertube.SearchDataPage.SearchResult> =
                    mutableListOf()

                if (content.musicCardShelfRenderer != null) {
                    type = 1
                    title = content.musicCardShelfRenderer
                        .header
                        ?.musicCardShelfHeaderBasicRenderer
                        ?.title
                        ?.text ?: ""

                    val searchResultTitle = content.musicCardShelfRenderer
                        .title
                        ?.runs
                        ?.firstOrNull()
                        ?.text ?: ""

                    val searchResultDesc = content.musicCardShelfRenderer
                        .subtitle?.text

                    val searchResultThumbnail = content.musicCardShelfRenderer
                        .thumbnail
                        ?.musicThumbnailRenderer
                        ?.thumbnail
                        ?.thumbnails
                        ?.let {
                            it.getOrNull(3) ?: it.getOrNull(2) ?: it.getOrNull(1)
                            ?: it.getOrNull(0)
                        }
                        ?.url ?: ""

                    val searchResultVideoId = content.musicCardShelfRenderer
                        .title
                        ?.runs
                        ?.firstOrNull()
                        ?.navigationEndpoint
                        ?.watchEndpoint
                        ?.videoId ?: ""

                    val searchResultBrowseId = content.musicCardShelfRenderer
                        .title
                        ?.runs
                        ?.firstOrNull()
                        ?.navigationEndpoint
                        ?.browseEndpoint
                        ?.browseId

                    val pageType = content.musicCardShelfRenderer
                        .title
                        ?.runs
                        ?.firstOrNull()
                        ?.navigationEndpoint
                        ?.browseEndpoint
                        ?.type

                    val result = Innertube.SearchDataPage.SearchResult(
                        title = searchResultTitle,
                        desc = searchResultDesc,
                        thumbnail = searchResultThumbnail,
                        videoId = searchResultVideoId,
                        browseId = searchResultBrowseId,
                        pageType = pageType
                    )
                    searchResultItemList.add(result)
                } else {
                    if (content.musicShelfRenderer != null) {
                        type = 2
                        title = content.musicShelfRenderer.title
                            ?.text ?: ""

                        query = content.musicShelfRenderer.bottomEndpoint
                            ?.searchEndpoint
                            ?.query ?: ""

                        params = content.musicShelfRenderer.bottomEndpoint
                            ?.searchEndpoint
                            ?.params ?: ""
                        continuation = content.musicShelfRenderer
                            .continuations
                            ?.firstOrNull()
                            ?.nextContinuationData
                            ?.continuation ?: ""
                        val itemContents = content.musicShelfRenderer.contents
                        if (itemContents != null) {
                            for (itemContent: MusicShelfRenderer.Content in itemContents) {
                                val item = Innertube.SearchDataPage.SearchResult(
                                    title = itemContent
                                        .musicResponsiveListItemRenderer
                                        ?.flexColumns
                                        ?.firstOrNull()
                                        ?.musicResponsiveListItemFlexColumnRenderer
                                        ?.text
                                        ?.runs
                                        ?.firstOrNull()
                                        ?.text,
                                    desc = itemContent.musicResponsiveListItemRenderer
                                        ?.flexColumns
                                        ?.get(1)
                                        ?.musicResponsiveListItemFlexColumnRenderer
                                        ?.text
                                        ?.runs
                                        ?.map { it.text }
                                        ?.joinToString("") ?: "",
                                    thumbnail = itemContent.musicResponsiveListItemRenderer
                                        ?.thumbnail
                                        ?.musicThumbnailRenderer
                                        ?.thumbnail
                                        ?.thumbnails
                                        ?.let { it.getOrNull(1) ?: it.getOrNull(0) }
                                        ?.url,
                                    videoId = itemContent.musicResponsiveListItemRenderer
                                        ?.flexColumns
                                        ?.firstOrNull()
                                        ?.musicResponsiveListItemFlexColumnRenderer
                                        ?.text
                                        ?.runs
                                        ?.firstOrNull()
                                        ?.navigationEndpoint
                                        ?.watchEndpoint
                                        ?.videoId,

                                    browseId = itemContent.musicResponsiveListItemRenderer
                                        ?.navigationEndpoint
                                        ?.browseEndpoint
                                        ?.browseId ?: "",

                                    pageType = itemContent.musicResponsiveListItemRenderer
                                        ?.navigationEndpoint
                                        ?.browseEndpoint
                                        ?.type,
                                )
                                //这两个ID必须有一个id是存在的，否则就不进入添加数据
                                if (!item.videoId.isNullOrBlank() || !item.browseId.isNullOrBlank()) {
                                    when (item.pageType) {
                                        "MUSIC_PAGE_TYPE_PODCAST_SHOW_DETAIL_PAGE" -> {
                                            //不add博客数据
                                        }

                                        "MUSIC_PAGE_TYPE_USER_CHANNEL" -> {
                                            //不add个人资料数据
                                        }

                                        else -> {
                                            searchResultItemList.add(item)
                                        }
                                    }

                                }
                            }
                        }
                    }
                }
                val dataPage =
                    Innertube.SearchDataPage(
                        type,
                        title = title,
                        searchResultList = searchResultItemList,
                        query = query,
                        params = params,
                        continuation = continuation
                    )
                searchDataPageList.add(dataPage)
            }
        }
        searchDataPageList
    }

suspend fun Innertube.moSearchPage(body: ContinuationBody): Result<Innertube.SearchDataPage>? =
    runCatchingNonCancellable {
        val response = client.post(search) {
            setBody(body)
        }.body<ContinuationResponse>()

        val searchResultItemList: MutableList<Innertube.SearchDataPage.SearchResult> =
            mutableListOf()

        val musicShelfContinuation = response.continuationContents
            ?.musicShelfContinuation

        val itemContents = musicShelfContinuation
            ?.contents
        if (itemContents != null) {
            for (itemContent: MusicShelfRenderer.Content in itemContents) {
                val item = Innertube.SearchDataPage.SearchResult(
                    title = itemContent
                        .musicResponsiveListItemRenderer
                        ?.flexColumns
                        ?.firstOrNull()
                        ?.musicResponsiveListItemFlexColumnRenderer
                        ?.text
                        ?.runs
                        ?.firstOrNull()
                        ?.text,
                    desc = itemContent.musicResponsiveListItemRenderer
                        ?.flexColumns
                        ?.get(1)
                        ?.musicResponsiveListItemFlexColumnRenderer
                        ?.text
                        ?.runs
                        ?.map { it.text }
                        ?.joinToString("") ?: "",
                    thumbnail = itemContent.musicResponsiveListItemRenderer
                        ?.thumbnail
                        ?.musicThumbnailRenderer
                        ?.thumbnail
                        ?.thumbnails
                        ?.let { it.getOrNull(1) ?: it.getOrNull(0) }
                        ?.url,
                    videoId = itemContent.musicResponsiveListItemRenderer
                        ?.flexColumns
                        ?.firstOrNull()
                        ?.musicResponsiveListItemFlexColumnRenderer
                        ?.text
                        ?.runs
                        ?.firstOrNull()
                        ?.navigationEndpoint
                        ?.watchEndpoint
                        ?.videoId,

                    browseId = itemContent.musicResponsiveListItemRenderer
                        ?.navigationEndpoint
                        ?.browseEndpoint
                        ?.browseId ?: "",

                    pageType = itemContent.musicResponsiveListItemRenderer
                        ?.navigationEndpoint
                        ?.browseEndpoint
                        ?.type,
                )
                //这两个ID必须有一个id是存在的，否则就不进入添加数据
                if (!item.videoId.isNullOrBlank() || !item.browseId.isNullOrBlank()) {
                    when (item.pageType) {
                        "MUSIC_PAGE_TYPE_PODCAST_SHOW_DETAIL_PAGE" -> {
                            //不add博客数据
                        }

                        "MUSIC_PAGE_TYPE_USER_CHANNEL" -> {
                            //不add个人资料数据
                        }

                        else -> {
                            searchResultItemList.add(item)
                        }
                    }

                }
            }
        }

        Innertube.SearchDataPage(
            searchResultList = searchResultItemList,
            continuation = musicShelfContinuation
                ?.continuations
                ?.firstOrNull()
                ?.nextContinuationData
                ?.continuation
        )
    }