package com.cwbuyer.main;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.RemoteViews;

import com.cwbuyer.format.KeySet;
import com.pwbuyer.main.R;

@SuppressWarnings("unused")
public class Widget extends AppWidgetProvider {

  private static RemoteViews views;
  private SharedPreferences sp;
  private String skin = "blue";
private String keyLang = "zh";
  private Context mycontext;
  Handler handler = new Handler();
  
  public static final String TAG = "latoos";
  
  public void onEnabled(Context context) {
    // TODO Auto-generated method stub
	UpdateService.registerService(context);
    super.onEnabled(context);
    
  }
  
  public void onDisabled(Context context) {
	context.stopService(new Intent(context, UpdateService.class));
    super.onDisabled(context);
  }

  public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    // main.setLang(context, main.keyLang);
    super.onUpdate(context, appWidgetManager, appWidgetIds);
    
    Log.e(TAG, "Widget onUpdate");
    
    final int N = appWidgetIds.length;

    sp = PreferenceManager.getDefaultSharedPreferences(context);
    skin = sp.getString("keyWSkin", "blue");
    keyLang = sp.getString("keyLang", "zh");
    mycontext = context;
    sp = null;
    // main.setLang(context, keyLang);
    if (skin == null) {
      skin = "blue";
    }

    ComponentName thisWidget = new ComponentName(context, Widget.class);

    UpdateService.registerService(context);
    context.startService(new Intent(context, UpdateService.class));

    for (int i = 0; i < N; i++) {
      int appWidgetId = appWidgetIds[i];

      views = new RemoteViews(context.getPackageName(), R.layout.widgetview);

      try {
    	  Intent intent1 = new Intent(context, MainMenu.class);
          PendingIntent pendingintent1 = PendingIntent.getActivity(context, 0, intent1, PendingIntent.FLAG_CANCEL_CURRENT);
          views.setOnClickPendingIntent(R.id.widget_btn_icon, pendingintent1);
      } catch (Exception e) {
      }

      try {
    	  // 搜尋
         Intent intent2 = new Intent(context, ManageItem.class);
         intent2.putExtra(KeySet.WIDGET, true);
         intent2.putExtra(KeySet.KEY_SEARCH, KeySet.SearchMode.WIDGET);
         PendingIntent pendingIntent2 = PendingIntent.getActivity(context, 0, intent2, PendingIntent.FLAG_CANCEL_CURRENT);
         views.setOnClickPendingIntent(R.id.widget_btn_search, pendingIntent2);
      } catch (Exception e) {
      }

      try {
    	  Bundle bundle3 = new Bundle();
          bundle3.putString("action", "wordmanage");
          Intent intent3 = new Intent(mycontext, AItem.class);
          intent3.putExtra("LatoosWidget", bundle3);
          intent3.putExtra(KeySet.WIDGET, true);
          PendingIntent pendingintent3 = PendingIntent.getActivity(mycontext, 0, intent3, PendingIntent.FLAG_CANCEL_CURRENT);
          views.setOnClickPendingIntent(R.id.widget_btn_add, pendingintent3);
      } catch (Exception e) {

      }
      appWidgetManager.updateAppWidget(appWidgetId, views);
    }
    super.onUpdate(context, appWidgetManager, appWidgetIds);

  }
  
  public void onDeleted(Context context, int[] appWidgetIds) {
		Log.e("engking", "Widget onDelete");
	    context.stopService(new Intent(context, UpdateService.class));
	    UpdateService.removeService(context);
	    super.onDeleted(context, appWidgetIds);
  }
  
  
  
  public static final class UpdateService extends Service {
	    public static PendingIntent serviceIntent = null;

	    private RemoteViews views;
	    private ComponentName thisWidget;
	    private AppWidgetManager manager;
	    private SharedPreferences sp;
	    private String skin = "blue";
	    private Context mycontext;
	    Handler handler = new Handler();
	    Handler handler2 = new Handler();
	    SQLiteDatabase db = null;
	    Cursor c = null;
	    
	    public static void registerService(Context context) {
	      AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

	      // 如果serviceIntent不為null(已註冊過)
	      if (serviceIntent != null)
	        alarmManager.cancel(serviceIntent); // 清除

	      final int updateInterval = 1000 * 60 * 10;// 間隔時間單位為ms
	      
	      // 間隔時間不為0
	      if (updateInterval != 0) {
	        // 如果serviceIntent為null
	        if (serviceIntent == null) {
	          // 建立intent
	          Intent intent = new Intent(context, UpdateService.class);
	          // 建立serviceIntent
	          serviceIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
	        }
	        // 在AlarmManager設定重覆執行的Server的intent
	        alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + updateInterval, updateInterval, serviceIntent);
	      }
	    }
	    
	    public void onCreate() {
	      super.onCreate();
	      
	      Log.e("engking", "Service onCreate");
	      
	      mycontext = this;
	      if (skin == null) {
	        skin = "blue";
	      }

	      views = new RemoteViews(getPackageName(), R.layout.widgetview);

	      // if (skin.equalsIgnoreCase("pink"))
	      // views = new RemoteViews(getPackageName(), R.layout.widgetview_pink);
	      // if (skin.equalsIgnoreCase("yellow"))
	      // views = new RemoteViews(getPackageName(), R.layout.widgetview_yellow);
	      // if (skin.equalsIgnoreCase("comp"))
	      // views = new RemoteViews(getPackageName(), R.layout.widgetview_comp);

	      thisWidget = new ComponentName(this, Widget.class);
	      manager = AppWidgetManager.getInstance(this);
	      
	    }

	    public static void removeService(Context context) {
	      if (serviceIntent != null) {
	        ((AlarmManager) context.getSystemService(Context.ALARM_SERVICE)).cancel(serviceIntent);
	        serviceIntent = null;
	      }
	    }
	    
	    public void onStart(Intent intent, int startId) {
	    	
	      /* 用一個新的線程來實現定時更新 */
	      sp = PreferenceManager.getDefaultSharedPreferences(this);
	      skin = sp.getString("keyWSkin", "");
	      sp = null;
	      // main.setLang(mycontext, keyLang);

	      if (skin == null) {
	        skin = "blue";
	      }
	      
	      try {
	    	  Intent intent1 = new Intent(mycontext, MainMenu.class);
	          PendingIntent pendingintent1 = PendingIntent.getActivity(mycontext, 0, intent1, PendingIntent.FLAG_CANCEL_CURRENT);
	          views.setOnClickPendingIntent(R.id.widget_btn_icon, pendingintent1);
	      } catch (Exception e) {
	      }

	      try {
	         Intent intent2 = new Intent(mycontext, ManageItem.class);
	         intent2.putExtra(KeySet.WIDGET, true);
	         intent2.putExtra(KeySet.KEY_SEARCH, KeySet.SearchMode.WIDGET);
	         PendingIntent pendingIntent2 = PendingIntent.getActivity(mycontext, 0, intent2, PendingIntent.FLAG_CANCEL_CURRENT);
	         views.setOnClickPendingIntent(R.id.widget_btn_search, pendingIntent2);
	      } catch (Exception e) {
	      }

	      try {
	    	  Bundle bundle3 = new Bundle();
	          bundle3.putString("action", "wordmanage");
	          Intent intent3 = new Intent(mycontext, AItem.class);
	          intent3.putExtra("LatoosWidget", bundle3);
	          intent3.putExtra(KeySet.WIDGET, true);
	          PendingIntent pendingintent3 = PendingIntent.getActivity(mycontext, 0, intent3, PendingIntent.FLAG_CANCEL_CURRENT);
	          views.setOnClickPendingIntent(R.id.widget_btn_add, pendingintent3);
	      } catch (Exception e) {
	      }
	       try { manager.updateAppWidget(thisWidget, views); } catch (Exception e) { }
	    }

		@Override
		public IBinder onBind(Intent intent) {
			// TODO Auto-generated method stub
			return null;
		}

	    public void onDestroy() {
	      Log.e("engking", "widget onDestroy");
	      getBaseContext().stopService(new Intent(getBaseContext(), UpdateService.class));
	      
	      super.onDestroy();
	    }
	}
}
