package net.ddns.mahaljsp.clockwidget;

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.util.Log;
import android.widget.RemoteViews;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * Created by Thomas Wu(mahaljsp@gmail.com) on 2016/12/24.
 */
public class ClockAppWidget extends AppWidgetProvider {
    public static final String ACTION_UPDATE="net.ddns.mahaljsp.ClockAppWidget.ACTION_UPDATE";
    static Intent intentService;//一定要使用static
    /*
            請注意, 書上寫的有錯誤
            每次安裝一個小工具到桌面, 就會new 出此類別的物件.
            而onEnable只有在第一次安裝時才會執行
             所以如果把intentService寫成物件變數, 則第二個小工具開始, 此intentService都是null
        */
    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {
        CharSequence widgetText = ClockAppWidgetConfigureActivity.loadTitlePref(context, appWidgetId);
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.clock_app_widget);
        views.setTextViewText(R.id.appwidget_text, widgetText);
        SimpleDateFormat sdf=new SimpleDateFormat("HH:mm");
        views.setTextViewText(R.id.now_text, sdf.format(new Date(System.currentTimeMillis())));
        PendingIntent pending=PendingIntent.getBroadcast(context, 0, new Intent(ACTION_UPDATE),
                PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.txtRefresh, pending);
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
    @Override
    public void onEnabled(Context context) {
        intentService=new Intent(context, ClockService.class);
        context.startService(intentService);
    }
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        for (int appWidgetId : appWidgetIds) {
            updateAppWidget(context, appWidgetManager, appWidgetId);
        }
    }
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        for (int appWidgetId : appWidgetIds) {
            ClockAppWidgetConfigureActivity.deleteTitlePref(context, appWidgetId);
        }
    }
    @Override
    public void onDisabled(Context context) {
        context.stopService(intentService);
        intentService=null;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals(ACTION_UPDATE)){
            AppWidgetManager manager=AppWidgetManager.getInstance(context);
            ComponentName cn=new ComponentName(context, ClockAppWidget.class);
            int[] appWidgetIds=manager.getAppWidgetIds(cn);
            onUpdate(context, manager, appWidgetIds);
        }
        else{
            super.onReceive(context, intent);//一定要有這行, 沒這行的話, 開機無法啟動
        }
    }
}

