package com.hi.music.player.network;

import com.hi.music.player.helper.CommonUtils;
import com.hi.music.player.javabean.response.ResponsePlay;
import com.hi.music.player.javabean.response.child.ResponseCategory;
import com.hi.music.player.javabean.response.ResponseHome;
import com.hi.music.player.javabean.response.child.ResponseHomeChild;
import com.hi.music.player.javabean.response.child.ResponseSingle;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class JsonHelper {


    public static ResponseHome ResolveHomeJson(JSONObject jsonObject) {
        ResponseHome responseHome = new ResponseHome();
        try {
            String bgUrl = getJsonUrl(jsonObject
                    .getJSONObject("background"));

            JSONObject sectionListRenderer = jsonObject
                    .getJSONObject("contents")
                    .getJSONObject("singleColumnBrowseResultsRenderer")
                    .getJSONArray("tabs")
                    .getJSONObject(0)
                    .getJSONObject("tabRenderer")
                    .getJSONObject("content")
                    .getJSONObject("sectionListRenderer");

            JSONObject responseContext = jsonObject
                    .getJSONObject("responseContext");
            JSONArray serviceTrackingParams = responseContext.getJSONArray("serviceTrackingParams");
            String visitorData = responseContext.getString("visitorData");
            CommonUtils.LogMsg("---------参数-visitorData=" + visitorData);

            responseHome.setBackgroundUrl(bgUrl);
            responseHome.setVisitorData(visitorData);
            getCommonHome(sectionListRenderer, responseHome);


        } catch (JSONException exception) {
            CommonUtils.LogMsg("----------exception=");
            exception.printStackTrace();

        }

        return responseHome;
    }


    public static ResponseHome ResolveHomeMoreJson(JSONObject jsonObject) {
        ResponseHome responseHome = new ResponseHome();
        try {

            JSONObject sectionListContinuation = jsonObject
                    .getJSONObject("continuationContents")
                    .getJSONObject("sectionListContinuation");


            JSONObject responseContext = jsonObject
                    .getJSONObject("responseContext");
            JSONArray serviceTrackingParams = responseContext.getJSONArray("serviceTrackingParams");

            getCommonHome(sectionListContinuation, responseHome);

        } catch (JSONException exception) {
            CommonUtils.LogMsg("----------exception=");
            exception.printStackTrace();

        }
        return responseHome;
    }


    public static List<ResponsePlay> ResolvePlayJson(JSONObject jsonObject) {
        List<ResponsePlay> list = new ArrayList<>();
        try {
            JSONObject playlistPanelRenderer = jsonObject.getJSONObject("contents")
                    .getJSONObject("singleColumnMusicWatchNextResultsRenderer")
                    .getJSONObject("tabbedRenderer")
                    .getJSONObject("watchNextTabbedResultsRenderer")
                    .getJSONArray("tabs")
                    .getJSONObject(0)
                    .getJSONObject("tabRenderer")
                    .getJSONObject("content")
                    .getJSONObject("musicQueueRenderer")
                    .getJSONObject("content")
                    .getJSONObject("playlistPanelRenderer");

            JSONArray contents = playlistPanelRenderer.getJSONArray("contents");

            for (int i = 0; i < contents.length(); i++) {
                ResponsePlay responsePlay = new ResponsePlay();
                JSONObject playlistPanelVideoRenderer = contents.getJSONObject(i)
                        .getJSONObject("playlistPanelVideoRenderer");

                String jsonUrl = getJsonUrl(playlistPanelVideoRenderer);
                String songName = getJsonTitle(playlistPanelVideoRenderer.getJSONObject("title"), 0);

                JSONObject longBylineText = playlistPanelVideoRenderer.getJSONObject("longBylineText");
                String singerName = getJsonTitle(longBylineText, 0);
                String AlbumTitle = getJsonTitle(longBylineText, 2);
                String YearRelease = getJsonTitle(longBylineText, 4);

                String SongDuration = getJsonTitle(playlistPanelVideoRenderer.getJSONObject("lengthText"), 0);

                String[] watchEndPoint = getWatchEndPoint(playlistPanelVideoRenderer);

                responsePlay.setCovert(jsonUrl);
                responsePlay.setSongTitle(songName);
                responsePlay.setSingerName(singerName);
                responsePlay.setAlbumTitle(AlbumTitle);
                responsePlay.setYear(YearRelease);
                responsePlay.setDuration(SongDuration);
                responsePlay.setVideoId(watchEndPoint[0]);
                responsePlay.setPlaylistId(watchEndPoint[1]);
                responsePlay.setParams(watchEndPoint[2]);
                responsePlay.setMusicVideoType(watchEndPoint[3]);

                list.add(responsePlay);
                CommonUtils.LogMsg("----------歌曲名字=" + songName + "---" + Arrays.toString(watchEndPoint));
            }


        } catch (JSONException exception) {
            CommonUtils.LogMsg("----------exception=");
            exception.printStackTrace();

        }
        return list;
    }


    private static void getCommonHome(JSONObject sectionListRenderer, ResponseHome responseHome) throws JSONException {


        JSONObject nextContinuationData = sectionListRenderer
                .getJSONArray("continuations")
                .getJSONObject(0)
                .getJSONObject("nextContinuationData");

        //token=continuation,cit= clickTrackingParams

        String clickTrackingParams = nextContinuationData.getString("clickTrackingParams");
        String continuation = nextContinuationData.getString("continuation");
        CommonUtils.LogMsg("---------参数---clickTrackingParams=" + clickTrackingParams);
        CommonUtils.LogMsg("---------参数--continuation=" + continuation);
        responseHome.setClickTrackingParams(clickTrackingParams);
        responseHome.setContinuation(continuation);

        JSONArray contents = sectionListRenderer
                .getJSONArray("contents");

        List<ResponseHomeChild> childList = new ArrayList<>();

        for (int i = 0; i < contents.length(); i++) {
            ResponseHomeChild responseHomeChild = new ResponseHomeChild();
            JSONObject object = contents.getJSONObject(i);

            JSONObject musicCarouselShelfRenderer = object.optJSONObject("musicCarouselShelfRenderer");
            if (musicCarouselShelfRenderer != null) {

                //模块标题
                String title = getJsonTitle(musicCarouselShelfRenderer
                        .getJSONObject("header")
                        .getJSONObject("musicCarouselShelfBasicHeaderRenderer")
                        .getJSONObject("title"), 0);
                CommonUtils.LogMsg("----------headertitle=" + title);
                responseHomeChild.setHeaderTitle(title);
                JSONArray childContents = musicCarouselShelfRenderer
                        .getJSONArray("contents");


                List<ResponseCategory> categoryList = new ArrayList<>();
                List<ResponseSingle> singleList = new ArrayList<>();
                for (int j = 0; j < childContents.length(); j++) {
                    JSONObject jsonList = childContents.getJSONObject(j);
                    JSONObject musicResponsiveListItemRenderer = jsonList.optJSONObject("musicResponsiveListItemRenderer");
                    if (musicResponsiveListItemRenderer != null) {
                        ResponseSingle responseSingle = new ResponseSingle();

                        String SingerHead = getJsonUrl(musicResponsiveListItemRenderer
                                .getJSONObject("thumbnail"));


                        JSONArray flexColumns = musicResponsiveListItemRenderer.getJSONArray("flexColumns");

                        //歌名、歌手名字、描述
                        String SongTitle = "";
                        String SingerName = "";
                        String Description = "";
                        for (int g = 0; g < flexColumns.length(); g++) {
                            JSONObject jsonObject = musicResponsiveListItemRenderer.getJSONArray("flexColumns")
                                    .getJSONObject(g)
                                    .getJSONObject("musicResponsiveListItemFlexColumnRenderer")
                                    .getJSONObject("text");
                            String text = getJsonTitle(jsonObject, 0);
                            if (g == 0) {
                                SongTitle = text;

                                JSONObject runs = jsonObject.getJSONArray("runs")
                                        .getJSONObject(0);

                                String[] watchEndPoint = getWatchEndPoint(runs);

                                responseSingle.setVideoId(watchEndPoint[0]);
                                responseSingle.setPlaylistId(watchEndPoint[1]);
                                responseSingle.setParams(watchEndPoint[2]);
                                responseSingle.setMusicVideoType(watchEndPoint[3]);

                            }
                            if (g == 1) SingerName = text;
                            if (g == 2) Description = text;
                        }
                        responseSingle.setSongTitle(SongTitle);
                        responseSingle.setSingerName(SingerName);
                        responseSingle.setSingerHead(SingerHead);
                        responseSingle.setDescription(Description);
                        singleList.add(responseSingle);
                        CommonUtils.LogMsg("      ----------111111111111----SongTitle=" + SongTitle + "--SingerName=" + SingerName + "---Description=" + Description + "--SingerHead=" + SingerHead);
                    }

                    JSONObject musicTwoRowItemRenderer = jsonList.optJSONObject("musicTwoRowItemRenderer");
                    if (musicTwoRowItemRenderer != null) {
                        ResponseCategory responseCategory = new ResponseCategory();
                        String covert = getJsonUrl(musicTwoRowItemRenderer
                                .getJSONObject("thumbnailRenderer"));

                        JSONObject title1 = musicTwoRowItemRenderer.getJSONObject("title");
                        String twoTitle = getJsonTitle(title1, 0);
                        String twoSubtitle = getJsonTextNew(musicTwoRowItemRenderer.getJSONObject("subtitle"));
//                        String pageType = title1.getJSONObject("navigationEndpoint")
//                                .getJSONObject("browseEndpoint")
//                                .getJSONObject("browseEndpointContextSupportedConfigs")
//                                .getJSONObject("browseEndpointContextMusicConfig")
//                                .getString("pageType");

                        responseCategory.setCovert(covert);
                        responseCategory.setTwoTitle(twoTitle);
                        responseCategory.setTwoSubtitle(twoSubtitle);
                        categoryList.add(responseCategory);
                        CommonUtils.LogMsg("      ----------2222222222----twoTitle=" + twoTitle + "-twoSubtitle=" + twoSubtitle);
                    }

                }
                responseHomeChild.setCategoryList(categoryList);
                responseHomeChild.setSingleList(singleList);
            }
            childList.add(responseHomeChild);
        }
        responseHome.setChildList(childList);


    }


    private static String[] getWatchEndPoint(JSONObject job) {

        String[] strings = new String[4];
        try {
            JSONObject watchEndpoint = job
                    .getJSONObject("navigationEndpoint")
                    .getJSONObject("watchEndpoint");
            if (watchEndpoint.has("videoId")) {
                strings[0] = watchEndpoint.getString("videoId");
            }
            if (watchEndpoint.has("playlistId")) {
                strings[1] = watchEndpoint.getString("playlistId");
            }
            if (watchEndpoint.has("params")) {
                strings[2] = watchEndpoint.getString("params");
            }
            if (watchEndpoint.has("watchEndpointMusicSupportedConfigs")) {
                strings[3] = watchEndpoint.getJSONObject("watchEndpointMusicSupportedConfigs")
                        .getJSONObject("watchEndpointMusicConfig")
                        .getString("musicVideoType");
            }
//          String videoId = watchEndpoint.getString("videoId");
//          String playlistId = watchEndpoint.getString("playlistId");
//          String params = watchEndpoint.getString("params");
//          String musicVideoType = watchEndpoint.getJSONObject("watchEndpointMusicSupportedConfigs")
//                  .getJSONObject("watchEndpointMusicConfig")
//                  .getString("musicVideoType");
        } catch (JSONException exception) {
            exception.printStackTrace();
        }
        return strings;
    }

    //取最大的一张图片
    private static String getJsonUrl(JSONObject jsonObject) {
        try {
            boolean b = jsonObject.has("musicThumbnailRenderer");
            if (b) {
                jsonObject = jsonObject.getJSONObject("musicThumbnailRenderer");
            }
            JSONArray jsonArray = jsonObject
                    .getJSONObject("thumbnail")
                    .getJSONArray("thumbnails");
            int length = jsonArray.length();
            CommonUtils.LogMsg("----------length=" + (length - 1));
            String pngUrl = jsonArray.getJSONObject(length - 1)
                    .getString("url");

            return pngUrl;
        } catch (JSONException exception) {
            return "";
        }
    }


    private static String getJsonTitle(JSONObject jsonObject, int index) {
        String text = "";
        try {
            JSONArray runs = jsonObject.getJSONArray("runs");
            if (index < runs.length()) {
                text = runs
                        .getJSONObject(index)
                        .getString("text");
            }

        } catch (JSONException exception) {
            exception.printStackTrace();
        }
        return text;
    }


    private static String getJsonTextNew(JSONObject jsonObject) {
        StringBuilder text = new StringBuilder();
        try {
            JSONArray runs = jsonObject.getJSONArray("runs");
            for (int i = 0; i < runs.length(); i++) {
                String text1 = runs.getJSONObject(i).getString("text");
                text.append(text1);
            }

        } catch (JSONException exception) {

        }
        return text.toString();
    }
}
