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.SectionListRenderer
import com.player.musicoo.innertube.models.bodies.BrowseBody
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.homePage(): Result<Innertube.BaseHomePage>? =
    runCatchingNonCancellable {

        val response = client.post(browse) {
            setBody(BrowseBody(Context.DefaultWeb, "FEmusic_home"))
        }.body<BrowseResponse>()

        val sectionListRenderer = response
            .contents
            ?.singleColumnBrowseResultsRenderer
            ?.tabs
            ?.firstOrNull()
            ?.tabRenderer
            ?.content
            ?.sectionListRenderer

        val contents = sectionListRenderer?.contents

        val visitorData = response.responseContext?.visitorData

        val continuations = sectionListRenderer?.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: SectionListRenderer.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)
                }
            }
        }
        val baseHomePage =
            Innertube.BaseHomePage(
                visitorData,
                cToken,
                cToken.toString(),
                itct.toString(),
                searchList
            )

        baseHomePage
    }