package com.example.providers;

import android.app.LoaderManager;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Loader;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Browser;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.ListFragment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class BrowserDataActivity extends FragmentActivity {
  private static final int BOOKMARKS_LOADER = 0;
  private static final int HISTORY_LOADER = 1;
  private static final int SEARCH_LOADER = 2;

  private static final String[] bookmarkColumns = {
      Browser.BookmarkColumns._ID,
      Browser.BookmarkColumns.TITLE,
      Browser.BookmarkColumns.URL,
      Browser.BookmarkColumns.BOOKMARK,
      Browser.BookmarkColumns.DATE,
      Browser.BookmarkColumns.CREATED,
      Browser.BookmarkColumns.VISITS
  };

  private static final String[] bookmarkFrom = {
      Browser.BookmarkColumns.TITLE, Browser.BookmarkColumns.URL };
  private static final int[] bookmarkTo = {
      R.id.bookmarkTitle, R.id.bookmarkUrl };
  private static final String bookmarkWhere
    = Browser.BookmarkColumns.BOOKMARK + " = 1";
  private static final String bookmarkOrderBy
    = Browser.BookmarkColumns.TITLE;

  private static final String[] historyFrom = {
      Browser.BookmarkColumns.TITLE, Browser.BookmarkColumns.URL };
  private static final int[] historyTo = {
      R.id.bookmarkTitle, R.id.bookmarkUrl
  };
  private static final String historyWhere = Browser.BookmarkColumns.BOOKMARK
      + " = 0";
  private static final String historyOrderBy = Browser.BookmarkColumns.DATE
      + " DESC";

  private static final String[] searchColumns = {
      Browser.SearchColumns._ID,
      Browser.SearchColumns.DATE,
      Browser.SearchColumns.SEARCH
  };

  private static final String[] searchFrom = {
    Browser.SearchColumns.SEARCH
  };
  private static final int[] searchTo = {
    R.id.bookmarkTitle
  };
  private static final String searchOrderBy = Browser.SearchColumns.DATE
      + " DESC";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
      finish();
      return;
    }

    if (savedInstanceState == null) {
      BrowserDataListFragment browserData = new BrowserDataListFragment();
      browserData.setArguments(getIntent().getExtras());
      getSupportFragmentManager().beginTransaction()
          .add(android.R.id.content, browserData).commit();
    }
  }

  public static class BrowserDataListFragment extends ListFragment implements
      LoaderManager.LoaderCallbacks<Cursor> {
    private int listToShow = BOOKMARKS_LOADER;
    private SimpleCursorAdapter scaBookmarks;
    private SimpleCursorAdapter scaHistory;
    private SimpleCursorAdapter scaSearch;
    private LoaderManager lm;

    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setHasOptionsMenu(true);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
      super.onActivityCreated(savedInstanceState);
      lm = getActivity().getLoaderManager();
      scaBookmarks = new SimpleCursorAdapter(getActivity(),
          R.layout.browser_bookmark_item, null, bookmarkFrom, bookmarkTo,
          CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
      scaHistory = new SimpleCursorAdapter(getActivity(),
          R.layout.browser_bookmark_item, null, historyFrom, historyTo,
          CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
      scaSearch = new SimpleCursorAdapter(getActivity(),
          R.layout.browser_bookmark_item, null, searchFrom, searchTo,
          CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
      lm.initLoader(BOOKMARKS_LOADER, null, this);
      lm.initLoader(HISTORY_LOADER, null, this);
      lm.initLoader(SEARCH_LOADER, null, this);

      switch (listToShow) {
        case BOOKMARKS_LOADER:
          this.setListAdapter(scaBookmarks);
          break;
        case HISTORY_LOADER:
          this.setListAdapter(scaHistory);
          break;
        case SEARCH_LOADER:
          this.setListAdapter(scaSearch);
          break;
      }

    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
      CursorLoader loader = null;
      switch (id) {
        case BOOKMARKS_LOADER:
          loader = new CursorLoader(getActivity(), Browser.BOOKMARKS_URI,
              bookmarkColumns, bookmarkWhere, null, bookmarkOrderBy);
          break;
        case HISTORY_LOADER:
          loader = new CursorLoader(getActivity(), Browser.BOOKMARKS_URI,
              bookmarkColumns, historyWhere, null, historyOrderBy);
          break;
        case SEARCH_LOADER:
          loader = new CursorLoader(getActivity(), Browser.SEARCHES_URI,
              searchColumns, null, null, searchOrderBy);
          break;
      }
      return loader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
      switch (loader.getId()) {
        case BOOKMARKS_LOADER:
          scaBookmarks.swapCursor(data);
          break;
        case HISTORY_LOADER:
          scaHistory.swapCursor(data);
          break;
        case SEARCH_LOADER:
          scaSearch.swapCursor(data);
          break;
      }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
      switch (loader.getId()) {
        case BOOKMARKS_LOADER:
          scaBookmarks.swapCursor(null);
          break;
        case HISTORY_LOADER:
          scaHistory.swapCursor(null);
          break;
        case SEARCH_LOADER:
          scaSearch.swapCursor(null);
          break;
      }
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
      super.onListItemClick(l, v, position, id);
      Uri uri;
      String[] columns;
      switch (listToShow) {
        case BOOKMARKS_LOADER:
          uri = Browser.BOOKMARKS_URI;
          columns = bookmarkColumns;
          break;
        case HISTORY_LOADER:
          uri = Browser.BOOKMARKS_URI;
          columns = bookmarkColumns;
          break;
        case SEARCH_LOADER:
          uri = Browser.SEARCHES_URI;
          columns = searchColumns;
          break;
        default:
          return;
      }
      uri = ContentUris.withAppendedId(uri, id);
      Cursor c = getActivity().getContentResolver().query(uri, columns, null,
          null, null);
      if (c.moveToFirst()) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < c.getColumnCount(); i++) {
          builder.append(c.getColumnName(i)).append(": ")
              .append(c.getString(i)).append("\n");
        }
        Toast.makeText(getActivity(), builder.toString(), Toast.LENGTH_LONG)
            .show();
      }
      c.close();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      super.onOptionsItemSelected(item);
      switch (item.getItemId()) {
        case R.id.browser_bookmarks:
          listToShow = BOOKMARKS_LOADER;
          this.setListAdapter(scaBookmarks);
          break;
        case R.id.browser_history:
          listToShow = HISTORY_LOADER;
          this.setListAdapter(scaHistory);
          break;
        case R.id.browser_search_history:
          listToShow = SEARCH_LOADER;
          this.setListAdapter(scaSearch);
          break;
        default:
          return false;
      }
      return true;
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
      super.onPrepareOptionsMenu(menu);
      switch (listToShow) {
        case BOOKMARKS_LOADER:
          menu.findItem(R.id.browser_bookmarks).setVisible(false);
          menu.findItem(R.id.browser_history).setVisible(true);
          menu.findItem(R.id.browser_search_history).setVisible(true);
          break;
        case HISTORY_LOADER:
          menu.findItem(R.id.browser_bookmarks).setVisible(true);
          menu.findItem(R.id.browser_history).setVisible(false);
          menu.findItem(R.id.browser_search_history).setVisible(true);
          break;
        case SEARCH_LOADER:
          menu.findItem(R.id.browser_bookmarks).setVisible(true);
          menu.findItem(R.id.browser_history).setVisible(true);
          menu.findItem(R.id.browser_search_history).setVisible(false);
          break;
      }
    }

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

  }
}