package com.example.providers;

import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.CursorAdapter;
import android.widget.SimpleCursorAdapter;

public class SettingsActivity extends FragmentActivity {
  private static final int SETTINGS_LOADER = 1;

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

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

  public static class SettingsListFragment extends ListFragment implements
      LoaderManager.LoaderCallbacks<Cursor> {
    private SimpleCursorAdapter sca;
    private static final String[] columns = {
        Settings.System._ID, Settings.System.NAME, Settings.System.VALUE
    };

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

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
      super.onActivityCreated(savedInstanceState);
      String[] from = new String[] {
          Settings.System.NAME, Settings.System.VALUE
      };
      int[] to = new int[] {
          R.id.settingName, R.id.settingValue
      };
      getLoaderManager().initLoader(SETTINGS_LOADER, null, this);
      sca = new SimpleCursorAdapter(getActivity(), R.layout.settings_item,
          null, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
      this.setListAdapter(sca);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
      CursorLoader loader = new CursorLoader(getActivity(), Settings.System.CONTENT_URI,
          columns, null, null, Settings.System.NAME);
      return loader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
      sca.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
      sca.swapCursor(null);
    }

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

  }
}