/*
 * ************************************************************************
 *
 * ADOBE SYSTEMS INCORPORATED
 * Copyright 2013 Adobe Systems Incorporated
 * All Rights Reserved.
 * NOTICE:  Adobe permits you to use, modify, and distribute this file in accordance with the 
 * terms of the Adobe license agreement accompanying it.  If you have received this file from a 
 * source other than Adobe, then your use, modification, or distribution of it requires the prior 
 * written permission of Adobe.
 *
 **************************************************************************
 */

package com.adobe.primetime.reference.ui.catalog;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import com.adobe.primetime.reference.PrimetimeReference;
import com.adobe.primetime.reference.R;
import com.adobe.primetime.reference.manager.EntitlementManager;
import com.adobe.primetime.reference.manager.ManagerFactory;
import com.adobe.primetime.reference.ui.player.PlayerActivity;

import java.util.ArrayList;

public class CatalogView extends Fragment {
	private final String LOG_TAG = PrimetimeReference.LOG_APP_NAME + "CatalogLiveView";

	private ArrayList<VideoItem> contentList = new ArrayList<VideoItem>();
	private ContentTileAdapter tileImageAdapter;

    private EntitlementManager entitlementManager = ManagerFactory.getEntitlementManager();
    private Activity attachedActivity;

	Handler handler = new Handler();

    @Override
    public void onAttach(Activity activity)
    {
        attachedActivity = activity;
        super.onAttach(activity);
    }

    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.fragment_catalog_content,
				container, false);

		tileImageAdapter = new ContentTileAdapter(getActivity(),
				R.layout.view_catalog_item, contentList);
		GridView gridView = (GridView) view.findViewById(R.id.gridView);
		gridView.setAdapter(tileImageAdapter);

		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {

				PrimetimeReference.logger.i(LOG_TAG + "#onItemClick", "Launching content.");

                // check if item requires entitlement authorization
                VideoItem videoItem = contentList.get(position);
                if (entitlementManager.requiresAuthorization(videoItem))
                {
                    entitlementManager.getAuthorization(videoItem, attachedActivity);
                }
                else
                {
                    // if an authorization request is pending, it means the user has already selected a video for playback
                    if (!entitlementManager.isAuthorizationPending())
                    {
                        startPlayerActivity(position);
                    }
                    else
                    {
                        PrimetimeReference.logger.d(LOG_TAG + "#onItemClick",
                                "Entitlement authorization is pending for another video item. Ignoring call to start new video item.");
                    }
                }

			}
		});

		return view;
	}


    private void startPlayerActivity(final int localPosition) {
        startPlayerActivity(contentList.get(localPosition));
    }

    private void startPlayerActivity(final VideoItem videoItem) {
		handler.post(new Runnable() {

			@Override
			public void run() {
				PrimetimeReference.logger.i(LOG_TAG + "#startPlayerActivity",
						"Launching content.");

				Intent intent = new Intent(getActivity(), PlayerActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
						| Intent.FLAG_ACTIVITY_SINGLE_TOP);
				intent.putExtra("CONTENT_INFO", videoItem);
				startActivity(intent);
			}
		});
	}

	synchronized public void updateContentList(ArrayList<VideoItem> contentList) {
		this.contentList.clear();
		this.contentList.addAll(contentList);

		if (tileImageAdapter != null) {
			tileImageAdapter.notifyDataSetChanged();
		}
	}

    public void refreshDataSet()
    {
        if (tileImageAdapter != null) {
            tileImageAdapter.notifyDataSetChanged();
        }
    }
}
