package com.eni.android.widget;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.widget.RemoteViews;

public class AirPlaneWidget extends AppWidgetProvider {
	private static final String AIRPLANE_MODE = "airplaneupdate";

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {

		Intent receiver = new Intent(context, AirPlaneWidget.class);
		receiver.setAction(AIRPLANE_MODE);
		receiver.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

		PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
				receiver, 0);
		RemoteViews views = new RemoteViews(context.getPackageName(),
				R.layout.widget_layout);
		views.setOnClickPendingIntent(R.id.airplane_btn, pendingIntent);
		appWidgetManager.updateAppWidget(appWidgetIds, views);
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		super.onReceive(context, intent);
		if (intent.getAction().equals(AIRPLANE_MODE)) {
			final RemoteViews views = new RemoteViews(context.getPackageName(),
					R.layout.widget_layout);

			boolean isAirplaneEnabled = false;
			if (Settings.System.getInt(context.getContentResolver(),
					Settings.System.AIRPLANE_MODE_ON, 0) != 0) {
				isAirplaneEnabled = true;
			}

			Settings.System
					.putInt(context.getContentResolver(),
							Settings.System.AIRPLANE_MODE_ON,
							isAirplaneEnabled ? 0 : 1);

			Intent changeMode = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
			changeMode.putExtra("state", !isAirplaneEnabled);
			context.sendBroadcast(changeMode);

			if (!isAirplaneEnabled) {
				views.setInt(R.id.airplane_btn, "setText", R.string.airplane_on);
			} else {
				views.setInt(R.id.airplane_btn, "setText",
						R.string.airplane_off);
			}

			AppWidgetManager appWidgetManager = AppWidgetManager
					.getInstance(context);
			appWidgetManager.updateAppWidget(new ComponentName(context,
					AirPlaneWidget.class), views);
		}
	}

}