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.Context
import com.player.musicoo.innertube.models.SectionListContinuation
import com.player.musicoo.innertube.models.bodies.BrowseMoreBody
import com.player.musicoo.innertube.utils.runCatchingNonCancellable
import io.ktor.client.call.body
import io.ktor.client.request.post
import io.ktor.client.request.setBody

suspend fun Innertube.homePageMore(
    baseHomePage: Innertube.BaseHomePage
): Result<Innertube.BaseHomePage>? =
    runCatchingNonCancellable {

        val defaultWeb = Context(
            client = Context.Client(
                clientName = "WEB_REMIX",
                clientVersion = "1.20220918",
                platform = "DESKTOP",
                visitorData = baseHomePage.visitorData
            )
        )

        val url =
            browse + "?ctoken=${baseHomePage.cToken}&continuation=${baseHomePage.continuation}&type=next&itct=${baseHomePage.itct}&prettyPrint=false"

        val response = client.post(url) {
            setBody(BrowseMoreBody(defaultWeb))
        }.body<BrowseResponse>()

        val sectionListContinuation = response
            .continuationContents
            ?.sectionListContinuation

        val contents = sectionListContinuation?.contents

        val visitorData = baseHomePage.visitorData//保存上次的data

        val continuations = sectionListContinuation?.continuations
        val nextContinuationData = continuations
            ?.firstOrNull()
            ?.nextContinuationData

        val cToken = nextContinuationData?.continuation
        val itct = nextContinuationData?.clickTrackingParams

        val searchList: MutableList<Innertube.HomePage> = mutableListOf()

        if (contents != null) {
            for (content: SectionListContinuation.Content in contents) {
                val text = content.musicCarouselShelfRenderer
                    ?.header
                    ?.musicCarouselShelfBasicHeaderRenderer
                    ?.title
                    ?.runs
                    ?.firstOrNull()
                    ?.text

                val homePage =
                    content.musicCarouselShelfRenderer?.contents?.let {
                        Innertube.HomePage(
                            text,
                            it
                        )
                    }
                if (homePage != null) {
                    searchList.add(homePage)
                }
            }
        }

        Innertube.BaseHomePage(
            visitorData,
            cToken,
            cToken.toString(),
            itct.toString(),
            searchList
        )
    }