package com.example.android.popularmovies;

import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;

import com.example.android.popularmovies.data.MovieContract.MovieEntry;


/**
 * A placeholder fragment containing a simple view.
 */
public class MainFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {


    private MoviesAdapter mMoviesAdapter;
    private TmdbAccess tmdbAccess;
    private BroadcastReceiver receiver;
    private String lastSortType;

    private static final int MAIN_LOADER = 0;


    private static final String[] MOVIE_COLUMNS = {
            MovieEntry._ID,
            MovieEntry.COLUMN_POSTER_PATH,
            MovieEntry.COLUMN_TITLE
    };

    // These indices are tied to MOVIE_COLUMNS.  If MOVIE_COLUMNS changes, these
    // must change.
    static final int COL_MOVIE_ID = 0;
    static final int COL_POSTER_PATH = 1;
    static final int COL_TITLE = 2;


    public MainFragment() {
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.e("PopularMovies", "onCreate " + getClass().getSimpleName());
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);

        // The CursorAdapter will take data from our cursor and populate the GridView
        // However, we cannot use FLAG_AUTO_REQUERY since it is deprecated, so we will end
        // up with an empty list the first time we run.
        tmdbAccess = new TmdbAccess(getContext());
        mMoviesAdapter = new MoviesAdapter(getActivity(), null, 0, tmdbAccess);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.e("PopularMovies", "onCreateView " + getClass().getSimpleName());
        View rootView = inflater.inflate(R.layout.fragment_discovery, container, false);

        // Get a reference to the ListView, and attach this adapter to it.
        GridView gridView = (GridView) rootView.findViewById(R.id.gridView_discovery);
        gridView.setAdapter(mMoviesAdapter);

//        gridView.setAdapter(mDiscoveryAdapter);
//        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Movie movie = mDiscoveryAdapter.getItem(position);
//                Intent intent = new Intent(getActivity(), DetailActivity.class);
//                intent.putExtra(Intent.EXTRA_TEXT, movie);
//                startActivity(intent);
//            }
//        });
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        Log.e("PopularMovies", "onActivityCreated " + getClass().getSimpleName());
        getLoaderManager().initLoader(MAIN_LOADER, null, this);
        super.onActivityCreated(savedInstanceState);
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.fragment_main, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_refresh) {
            syncDB();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onStart() {
        receiver = new InternetReceiver(getActivity()) {
            @Override
            protected void refresh() {
                syncDB();
            }

        };
        getLoaderManager().restartLoader(MAIN_LOADER, null, this);
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        getActivity().registerReceiver(receiver, filter);
        super.onStart();
    }


    public void syncDB() {
        String sortOrder = Utility.getSortOrderPreferences(getContext());
        if ((lastSortType == null) || !sortOrder.equals(lastSortType)) {
            FetchMoviesTask movieTask = new FetchMoviesTask();
            movieTask.execute(sortOrder);
            lastSortType = sortOrder;
        }
    }

    @Override
    public void onStop() {
        getActivity().unregisterReceiver(receiver);
        super.onStop();
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        Log.e("PopularMovies", "onCreateLoader " + getClass().getSimpleName());
        return new CursorLoader(getActivity(),
                MovieEntry.buildMovieSortByUri(Utility.getSortOrderPreferences(getContext())),
                MOVIE_COLUMNS,
                null,
                null,
                null);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        Log.e("PopularMovies", "onLoadFinished " + getClass().getSimpleName());
        mMoviesAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        Log.e("PopularMovies", "onLoaderReset " + getClass().getSimpleName());
        mMoviesAdapter.swapCursor(null);
    }


    public class FetchMoviesTask extends AsyncTask<String, Void, Cursor> {

        private static final String LOG_TAG = "PopularMovies";

        @Override
        protected Cursor doInBackground(String... params) {
            tmdbAccess.syncMovies(params[0]);
//            Cursor cur = getActivity().getContentResolver().query(
//                    MovieEntry.buildMovieSortByUri(Utility.getSortOrderPreferences(getContext())),
//                    MOVIE_COLUMNS,
//                    null,
//                    null,
//                    null);
            return null;
        }

//        @Override
//        protected void onPostExecute(Cursor result) {
//            if (result != null) {
//                //mDiscoveryAdapter.refresh(result);
//                mMoviesAdapter.changeCursor(result);
//            }
//        }

    }

}

@@ -75,24 +75,55 @@
 stReceiver;%0A
+import android.content.Intent;%0A
 import andro
@@ -657,16 +657,51 @@
 wGroup;%0A
+import android.widget.AdapterView;%0A
 import a
@@ -2666,60 +2666,8 @@
 );%0A%0A
-//        gridView.setAdapter(mDiscoveryAdapter);%0A//
     
@@ -2738,26 +2738,24 @@
 istener() %7B%0A
-//
             
@@ -2756,34 +2756,32 @@
       @Override%0A
-//
             publ
@@ -2855,26 +2855,24 @@
  long id) %7B%0A
-//
             
@@ -2879,61 +2879,111 @@
     
-Movie movie = mDiscoveryAdapter.getItem(position);%0A//
+Cursor cursor = (Cursor) parent.getItemAtPosition(position);%0A                if (cursor != null) %7B%0A    
     
@@ -3059,18 +3059,20 @@
 class);%0A
-//
+    
         
@@ -3090,46 +3090,83 @@
 ent.
-putExtra(Intent.EXTRA_TEXT, movie);%0A//
+setData(MovieEntry.buildMovieDetailUri(cursor.getLong(COL_MOVIE_ID)));%0A    
     
@@ -3196,26 +3196,28 @@
 ty(intent);%0A
-//
+    
             
@@ -3210,34 +3210,46 @@
               %7D%0A
-//
+            %7D%0A
         %7D);%0A    

Add onClickListener with uri Intent