package com.minano.themovielibrary.helpers;

import android.util.Log;

import com.minano.themovielibrary.models.DetailItem;
import com.minano.themovielibrary.models.TVShowItem;

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

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

/**
 * Created by Admin on 10/09/2016.
 */
public class TVShowJSONParser implements ITVShowJSONParser {
    final static String TAG = "TVShowJSONParser";

    @Override
    public TVShowItem parseResponse(String response) {
        Log.d(TAG, response);
        TVShowItem tvShowItem = new TVShowItem();
        try {
            JSONObject jsonObject = new JSONObject(response);
            tvShowItem.setId(jsonObject.getInt("id"));
            tvShowItem.setTitle(jsonObject.getString("original_name"));
            tvShowItem.setFirstAirDate(jsonObject.getString("first_air_date"));
            tvShowItem.setPoints(jsonObject.getInt("vote_average"));
            tvShowItem.setVotes(jsonObject.getInt("vote_count"));
            tvShowItem.setImageUrl(jsonObject.getString("poster_path"));
//            tvShowItem.setBudget(jsonObject.getString("budget"));
//            tvShowItem.setRevenue(jsonObject.getString("revenue"));
            tvShowItem.setStatus(jsonObject.getString("status"));
            JSONArray genreArray = (JSONArray) jsonObject.get("genres");
            tvShowItem.setGenre(getFields(genreArray));
            JSONArray productionCompaniesArray = (JSONArray) jsonObject.get("production_companies");
            tvShowItem.setProductionCompanies(getFields(productionCompaniesArray));
            JSONArray episodeRuntimeArray = (JSONArray) jsonObject.get("episode_run_time");
            tvShowItem.setEpisodeRuntime((int)episodeRuntimeArray.get(0));
            tvShowItem.setNumberOfEpisodes(jsonObject.getInt("number_of_episodes"));
            tvShowItem.setNumberOfSeasons(jsonObject.getInt("number_of_seasons"));
//            tvShowItem.setTagline(jsonObject.getString("tagline"));
            tvShowItem.setOverview(jsonObject.getString("overview"));
//            tvShowItem.setHasVideo(jsonObject.getBoolean("video"));
//            if(tvShowItem.hasVideo())
//                tvShowItem.setVideoKey(jsonObject.getString("video_key"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return tvShowItem;
    }

    private String getFields(JSONArray jsonArray){
        StringBuilder builder = new StringBuilder();
        for(int i = 0 ; i<jsonArray.length(); i++)
        {
            try {
                JSONObject object = jsonArray.getJSONObject(i);
                builder.append(object.get("name"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if(i<jsonArray.length()-1)
                builder.append(", ");
        }
        return builder.toString();
    }
}
