package kimiko.coreen.app.cours;


import kimiko.coreen.app.cours.tools.GridVocAdapter;
import kimiko.coreen.app.cours.tools.achat.ServiceConnectionApp;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.GridView;
import android.widget.Switch;
import android.widget.Toast;
import android.support.v4.widget.DrawerLayout;

public class MainActivity extends Activity implements NavigationDrawerFragment.NavigationDrawerCallbacks {

	/**
	 * Fragment managing the behaviors, interactions and presentation of the
	 * navigation drawer.
	 */
	private NavigationDrawerFragment mNavigationDrawerFragment;

	/**
	 * Used to store the last screen title. For use in
	 * {@link #restoreActionBar()}.
	 */

	static boolean prenium=false;
	private static final ServiceConnectionApp SERVICECONNECTION = new ServiceConnectionApp();
	private static final String BILLING_ITEM = "kimiko.coreen.cours.lecons";
	//private static final String BILLING_ITEM = "android.test.purchased";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
		serviceIntent.setPackage("com.android.vending");
		bindService(serviceIntent, SERVICECONNECTION, Context.BIND_AUTO_CREATE);


		mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.navigation_drawer);
		getActionBar().setDisplayShowTitleEnabled(true);

		// Set up the drawer.
		mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		Intent intent = getIntent();
	    String action = intent.getAction();
	    if(action==null)
	    	return;
	    Log.d("action", action);
	    if(action.equals("android.intent.action.VIEW"))
	    {
	    	Uri data = intent.getData();
	    	String id = data.getQueryParameter("id");
	    	if(id!=null)
	    		onNavigationDrawerItemSelected(0, Integer.valueOf(id)-1);
	    }
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1001) {
			if (resultCode == RESULT_OK) {
				Toast.makeText(this, R.string.achat_effectue, Toast.LENGTH_SHORT).show();
			}
		}
	}
	private void achatDialog()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.achat_explication)
		.setPositiveButton(R.string.achat_oui, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				if(achat())
					Toast.makeText(getApplicationContext(), R.string.achat_deja_effectue, Toast.LENGTH_SHORT).show();
			}
		})
		.setNegativeButton(R.string.achat_non, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
			}
		});
		AlertDialog dialog = builder.create();
		dialog.show();
	}

	private boolean achat()
	{
		try {
			if(SERVICECONNECTION.getmService()!=null)
			{
				Bundle buyIntentBundle = SERVICECONNECTION.getmService().getBuyIntent(3, getPackageName(), BILLING_ITEM, "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
				int resCode = buyIntentBundle.getInt("RESPONSE_CODE");
				if(resCode==0)
				{
					PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
					startIntentSenderForResult(pendingIntent.getIntentSender(), 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
				}
				else if(resCode==7)
				{
					MainActivity.prenium=true;
					return true;
				}
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (SendIntentException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void onNavigationDrawerItemSelected(int groupPosition, int childPosition) {
		FragmentManager fragmentManager = getFragmentManager();
		fragmentManager.beginTransaction()
		.replace(R.id.container, PlaceholderFragment.newInstance(groupPosition, childPosition)).commit();
	}
	
	@Override
	public void checkPrenium() {
		achat();
	}

	//public void restoreActionBar() {
	//	ActionBar actionBar = getActionBar();
	//	actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
	//	actionBar.setDisplayShowTitleEnabled(true);
	//	actionBar.setTitle(mTitle);
	//}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (!mNavigationDrawerFragment.isDrawerOpen()) {
			// Only show items in the action bar relevant to this screen
			// if the drawer is not showing. Otherwise, let the drawer
			// decide what to show in the action bar.
			getMenuInflater().inflate(R.menu.main, menu);
			//restoreActionBar();
			return true;
		}
		return super.onCreateOptionsMenu(menu);
	}

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

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		private static final String ARG_SECTION_NUMBER = "section_number";
		private static final String ARG_SECTION_CHILDNUMBER = "section_child_number";
		/**
		 * Returns a new instance of this fragment for the given section number.
		 * @param childPosition 
		 */
		public static PlaceholderFragment newInstance(int sectionNumber, int childPosition) {
			PlaceholderFragment fragment = new PlaceholderFragment();
			Bundle args = new Bundle();
			args.putInt(ARG_SECTION_NUMBER, sectionNumber);
			args.putInt(ARG_SECTION_CHILDNUMBER, childPosition);
			fragment.setArguments(args);
			return fragment;
		}

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			int section = getArguments().getInt(ARG_SECTION_NUMBER);
			int index = getArguments().getInt(ARG_SECTION_CHILDNUMBER);
			if(section==0)
			{
				View rootView = inflater.inflate(R.layout.fragment_main, container, false);
				getActivity().getActionBar().setTitle(getResources().getStringArray(R.array.lecon)[index]);
				((WebView) rootView.findViewById(R.id.item_detail)).loadUrl(getResources().getStringArray(R.array.lien)[index]);
				return rootView;
			}
			//else
			//{
				View rootView = inflater.inflate(R.layout.fragment_voc, container, false);
				getActivity().getActionBar().setTitle(getResources().getStringArray(R.array.vocabulaire)[index]);
				String type = getResources().getStringArray(R.array.vocLien)[index];
				int id = getResources().getIdentifier("voc_"+type, "array", getActivity().getPackageName());
				int idTrad = getResources().getIdentifier("voc_"+type+"_trad", "array", getActivity().getPackageName());
				int idRom = getResources().getIdentifier("voc_"+type+"_rom", "array", getActivity().getPackageName());
				
				Switch switchView = ((Switch) rootView.findViewById(R.id.switchTradSelec));
				Switch switchView2 = ((Switch) rootView.findViewById(R.id.switchTradTout));
				GridView gridView = ((GridView) rootView.findViewById(R.id.gridViewVoc));
				final GridVocAdapter gridVocAdapter = new GridVocAdapter(getActivity(), getResources().getStringArray(id),
						getResources().getStringArray(idRom),
						getResources().getStringArray(idTrad));
				
				switchView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						gridVocAdapter.cacher(isChecked);
						gridVocAdapter.notifyDataSetChanged();
					}
				});
				switchView2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						gridVocAdapter.cacherTout(isChecked);
						gridVocAdapter.notifyDataSetChanged();
					}
				});
				gridView.setAdapter(gridVocAdapter);
				
			//}
			return rootView;
		}
	}
}
