package com.hi.music.player.network;

import com.google.gson.Gson;
import com.hi.music.player.MusicApplication;
import com.hi.music.player.api.RequestListener;
import com.hi.music.player.javabean.requestbody.BodyHome;
import com.hi.music.player.javabean.requestbody.BodyPlay;
import com.hi.music.player.javabean.requestbody.BodyPlayUrl;
import com.hi.music.player.javabean.requestbody.BodySearch;
import com.hi.music.player.javabean.requestbody.BodySearchSuggestion;
import com.hi.music.player.javabean.requestbody.child.Client;
import com.hi.music.player.javabean.requestbody.child.ContextBody;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitManager {

    private String base_Host = "https://music.youtube.com/";

    private String base_Host_test = "https://rr2---sn-tt1e7nlz.googlevideo.com/";
    private static volatile RetrofitManager REQUEST_MANAGER;

    private Retrofit retrofit;
    public MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private MusicApi musicApi;

    private String header1 = "playlistPanelVideoRenderer(title,navigationEndpoint,longBylineText,shortBylineText,thumbnail,lengthText)";
    private String header = "contents.singleColumnMusicWatchNextResultsRenderer.tabbedRenderer.watchNextTabbedResultsRenderer.tabs.tabRenderer.content.musicQueueRenderer.content.playlistPanelRenderer(continuations,contents(automixPreviewVideoRenderer," + header1 + "))";

    private RetrofitManager() {

        musicApi = getRetrofit().create(MusicApi.class);
    }
    private synchronized Retrofit getRetrofit() {
        if (retrofit == null) {
            long DEFAULT_TIMEOUT = 5;
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                    .addInterceptor(httpLoggingInterceptor)
                    .build();
            retrofit = new Retrofit.Builder()
                    .baseUrl(base_Host)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }
        return retrofit;
    }

    public static RetrofitManager getInstance() {
        if (REQUEST_MANAGER == null) {
            synchronized (RetrofitManager.class) { //锁,防止线程问题
                if (REQUEST_MANAGER == null) {
                    REQUEST_MANAGER = new RetrofitManager();
                }
            }
        }
        return REQUEST_MANAGER;
    }


    public void getHomeData(RequestListener<ResponseBody> requestListener) {
        BodyHome bodyHome = new BodyHome();
        Gson gson = new Gson();
        String s = gson.toJson(bodyHome);
        RequestBody requestBody = RequestBody.Companion.create(s, JSON);
        musicApi.getHomeData(requestBody)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ObserverWrapper<ResponseBody>(requestListener));
    }

    public void getHomeMoreData(String continuation, String itct, String visitorData, RequestListener<ResponseBody> requestListener) {
        BodyHome bodyHome = new BodyHome();
        bodyHome.getContext().getClient().setVisitorData(visitorData);
        Gson gson = new Gson();
        String s = gson.toJson(bodyHome);
        RequestBody requestBody = RequestBody.Companion.create(s, JSON);

        HashMap<String, String> stringHashMap = new HashMap<>();
        stringHashMap.put("ctoken", continuation);
        stringHashMap.put("continuation", continuation);
        stringHashMap.put("type", "next");
        stringHashMap.put("itct", itct);
        stringHashMap.put("prettyPrint", "false");
        musicApi.getHomeMoreData(continuation, continuation, "next", itct, false, requestBody)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ObserverWrapper<ResponseBody>(requestListener));
    }


    public void getPlayList(String params, String playlistId, String videoId, String musicVideoType, RequestListener<ResponseBody> requestListener) {
        BodyPlay bodyPlay = new BodyPlay();
        bodyPlay.setParams(params);
        bodyPlay.setPlaylistId(playlistId);
        bodyPlay.setVideoId(videoId);
        bodyPlay.getWatchEndpointMusicSupportedConfigs().setMusicVideoType(musicVideoType);
        Gson gson = new Gson();
        String s = gson.toJson(bodyPlay);
        RequestBody requestBody = RequestBody.Companion.create(s, JSON);
        musicApi.getMusicPlayPage(header, requestBody)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ObserverWrapper<ResponseBody>(requestListener));
    }


    public void getPlayUrl(String videoId, RequestListener<ResponseBody> requestListener) {
        BodyPlayUrl bodyPlay = new BodyPlayUrl();
        bodyPlay.setVideoId(videoId);
        Client client = bodyPlay.getContext().getClient();
        client.setClientName("ANDROID");
        client.setClientVersion("19.05.36");
        client.setPlatform("DESKTOP");
        String visitorData = MusicApplication.getVisitorData();
//        client.setVisitorData("CgtWN1RXaURPN3LNZyiZK9e4BjIKCgJVUXIEGgAgPW%3D%3D");
        client.setVisitorData(visitorData);
//        bodyPlay.getContext().getThirdParty().setEmbedUrl("https://www.youtube.com/watch?v="+videoId);


        Gson gson = new Gson();
        String s = gson.toJson(bodyPlay);
        RequestBody requestBody = RequestBody.Companion.create(s, JSON);
        musicApi.getMusicPlayUrl(requestBody)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ObserverWrapper<ResponseBody>(requestListener));
    }


    public void getCategoryList(String browserId, RequestListener<ResponseBody> requestListener) {
        BodyHome bodyHome = new BodyHome();
        bodyHome.setBrowseId(browserId);
//        bodyHome.setBrowseId("VLPLI-asvmHZWNo_xjMMfD_v2O2lTyCdrjaK");

        Client client = bodyHome.getContext().getClient();
        client.setClientVersion("1.20240506.01.00");


        Gson gson = new Gson();
        String s = gson.toJson(bodyHome);
        RequestBody requestBody = RequestBody.Companion.create(s, JSON);


        musicApi.getCategoryList(requestBody)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ObserverWrapper<>(requestListener));
    }




    public void getSearchSuggestion(String input, RequestListener<ResponseBody> requestListener) {
        BodySearchSuggestion body = new BodySearchSuggestion();
        body.setInput(input);
        Client client = body.getContext().getClient();
        client.setClientVersion("1.20240506.01.00");
        Gson gson = new Gson();
        String s = gson.toJson(body);
        RequestBody requestBody = RequestBody.Companion.create(s, JSON);
        musicApi.getSearchSuggestion(requestBody)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ObserverWrapper<>(requestListener));
    }


    public void getSearch(String query, RequestListener<ResponseBody> requestListener) {
        BodySearch body = new BodySearch();
        body.setQuery(query);
        Client client = body.getContext().getClient();
        client.setClientVersion("1.20240506.01.00");
        Gson gson = new Gson();
        String s = gson.toJson(body);
        RequestBody requestBody = RequestBody.Companion.create(s, JSON);
        musicApi.getSearch(requestBody)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ObserverWrapper<>(requestListener));
    }
}
