/* Copyright (c) 2014 Andrea Zoli. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file. */

package it.inaf.android;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.widget.Toast;

import com.android.volley.VolleyError;

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

import java.util.ArrayList;

public class VideoGalleryActivity extends NavigationDrawerActivity
        implements JSONRequestFragment.Callbacks, VideoGalleryFragment.Callbacks {

    private static final String mYoutubeFeedUrl = "http://gdata.youtube.com/feeds/api/users/inaftv/uploads?alt=json&max-results=50";
    private Bundle mArgs;
    private ArrayList<VideoItem> mItemList = null;
    public static final int JSON_VIDEO_YOUTUBE = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FragmentManager fm = getSupportFragmentManager();
        JSONRequestFragment requestYoutubeJson = (JSONRequestFragment) fm.findFragmentByTag("json_request_youtube");

        if(savedInstanceState != null) {
            mArgs = savedInstanceState.getBundle("args");
        }
        else {
            mArgs = getIntent().getExtras();
        }

        mItemList = (ArrayList<VideoItem>) mArgs.getSerializable("item_list");

        // if there is no request ongoing and no previous request results
        if(requestYoutubeJson == null && mItemList == null)
        {
            requestYoutubeJson = new JSONRequestFragment();
            fm.beginTransaction().add(requestYoutubeJson, "json_request_youtube").commit();
            requestYoutubeJson.start(VideoGalleryActivity.JSON_VIDEO_YOUTUBE, mYoutubeFeedUrl, false);
            startLoading();
        }
        else {
            addFragment();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBundle("args", mArgs);
        if(mItemList != null)
            outState.putSerializable("item_list", mItemList);
    }

    @Override
    public void onResponseArray(int id, JSONArray response) {
    }

    @Override
    public void onResponse(int id, JSONObject response) {
        if (id == JSON_VIDEO_YOUTUBE) {

            mItemList = new ArrayList<VideoItem>();

            try {
                JSONArray entries = response.getJSONObject("feed").getJSONArray("entry");

                for(int i=0; i<entries.length(); i++)
                {
                    VideoItem item = new VideoItem();

                    JSONObject entry = entries.getJSONObject(i);
                    item.title = entry.getJSONObject("title").getString("$t");
                    String url = entry.getJSONObject("id").getString("$t");
                    String youtubeId = url.substring(url.replaceAll("\\\\", "/").lastIndexOf("/"));
                    item.videoUrl = "<body style='margin:0;padding:0;'><div class='embed-container'><iframe src=\"http://www.youtube.com/embed/" + youtubeId + "?modestbranding=1&showinfo=0\" frameborder=\"0\" allowfullscreen></iframe></div></body>";
                    item.date = DateFormatter.formatType2(entry.getJSONObject("published").getString("$t"));
                    item.thumbnailUrl = entry.getJSONObject("media$group").getJSONArray("media$thumbnail").getJSONObject(0).getString("url");
                    item.visualizationCounter = entry.getJSONObject("yt$statistics").getString("viewCount");
                    item.description = entry.getJSONObject("content").getString("$t");

                    mItemList.add(item);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

            addFragment();
        }
    }

    @Override
    public void onError(VolleyError error) {
        Toast.makeText(this, "Connessione lenta o assente. Controllare le impostazioni di connessione e ritentare.", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onItemSelected(Bundle args) {
/*      if (mTwoPane) { TODO handle item selection
            // In two-pane mode, show the detail view in this activity by
            // adding or replacing the detail fragment using a
            // fragment transaction.
            Bundle arguments = new Bundle();
            arguments.putString(FeedDetailFragment.ARG_ITEM_ID, args.getString(ITEM_ID));
            FeedDetailFragment fragment = new FeedDetailFragment();
            fragment.setArguments(arguments);
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.item_detail_container, fragment)
                    .commit();
        }*/
        Intent intent = new Intent(this, VideoDetailActivity.class);
        intent.putExtras(args);
        intent.putExtra("top_activity", false);
        startActivity(intent);
        overridePendingTransition(0, 0);
    }

    void addFragment() {
        Bundle args = new Bundle();
        args.putString("title", mTitle);
        args.putSerializable("item_list", mItemList);
        VideoGalleryFragment fragment = new VideoGalleryFragment();
        fragment.setArguments(args);
        FragmentManager fm = getSupportFragmentManager();
        fm.beginTransaction()
                .add(R.id.container, fragment, "fragment_container").commit();
        stopLoading();
    }
}

@@ -686,80 +686,49 @@
 p://
-gdata.youtube.com/feeds/api/users/inaftv/uploads?alt=json&max-results=50
+app.media.inaf.it/GetYoutubeVideoList.php
 %22;%0A 
@@ -2456,22 +2456,20 @@
 ONArray 
-entrie
+item
 s = resp
@@ -2477,30 +2477,8 @@
 nse.
-getJSONObject(%22feed%22).
 getJ
@@ -2487,21 +2487,21 @@
 NArray(%22
-entry
+items
 %22);%0A%0A   
@@ -2528,22 +2528,20 @@
  i=0; i%3C
-entrie
+item
 s.length
@@ -2657,22 +2657,21 @@
 ect 
-entry = entrie
+joItem = item
 s.ge
@@ -2710,125 +2710,106 @@
     
-item.title = entry.getJSONObject(%22title%22).getString(%22$t%22);%0A                    String url = entry.getJSONObject(%22id%22)
+JSONObject joSnippet = joItem.getJSONObject(%22snippet%22);%0A                    item.title = joSnippet
 .get
@@ -2812,26 +2812,29 @@
 .getString(%22
-$
 t
+itle
 %22);%0A        
@@ -2868,66 +2868,29 @@
 d = 
-url.substring(url.replaceAll(%22%5C%5C%5C%5C%22, %22/%22).lastIndexOf(%22/%22)
+joItem.getString(%22id%22
 );%0A 
@@ -3200,53 +3200,39 @@
 pe2(
-entry.getJSONObject(%22published%22).getString(%22$
+joSnippet.getString(%22publishedA
 t%22))
@@ -3273,21 +3273,25 @@
 ilUrl = 
-entry
+joSnippet
 .getJSON
@@ -3302,42 +3302,8 @@
 ct(%22
-media$group%22).getJSONArray(%22media$
 thum
@@ -3307,16 +3307,17 @@
 humbnail
+s
 %22).getJS
@@ -3325,17 +3325,25 @@
 NObject(
-0
+%22default%22
 ).getStr
@@ -3402,21 +3402,22 @@
 unter = 
-entry
+joItem
 .getJSON
@@ -3428,11 +3428,8 @@
 ct(%22
-yt$
 stat
@@ -3504,38 +3504,17 @@
 n = 
-entry.getJSONObject(%22content%22)
+joSnippet
 .get
@@ -3525,10 +3525,19 @@
 ng(%22
-$t
+description
 %22);%0A

Fix youtube video list json to use google api v3 (from server).