package com.zoblak.farm;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.os.PowerManager;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class AlarmPollingService extends IntentService {
    // TODO: Rename actions, choose action names that describe tasks that this
    // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
    private static final String ACTION_PING = "com.zoblak.apps.farmalarm.action.PING";
    private static final String ACTION_STOP_ALARM = "com.zoblak.apps.farmalarm.action.STOP_ALARM";

    // TODO: Rename parameters
    private static final String CONTROLLERS = "com.zoblak.apps.farmalarm.extra.CONTROLLLERS";

    private AlarmResponseHandler handler;


    public AlarmPollingService() {
        super("AlarmPollingService");
    }

    /**
     * Starts this service to perform action Foo with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    public static void startActionPing(Context context, String controllers) {
        Intent intent = new Intent(context, AlarmPollingService.class);
        intent.setAction(ACTION_PING);
        intent.putExtra(CONTROLLERS, controllers);
        context.startService(intent);
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_PING.equals(action)) {
                final String controllers = intent.getStringExtra(CONTROLLERS);
                handleActionPing(controllers);
            }
        }
    }

    /**
     * Handle action Foo in the provided background thread with the provided
     * parameters.
     */
    private void handleActionPing(String controllers) {

        PowerManager powerManager = (PowerManager) this.getSystemService(POWER_SERVICE);
        PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                "AlarmPingerWakeLock");
        wakeLock.acquire();
        ZoblakClient zc = new ZoblakClient(controllers);
        handler = new AlarmResponseHandler(this,zc.PingServer());
        handler.handle();

        wakeLock.release();

    }

}
