package com.ericsson.uecontrol.gui.fragments;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;

import com.ericsson.uecontrol.R;
import com.ericsson.uecontrol.core.util.StringUtil;
import com.ericsson.uecontrol.core.util.ThroughputCalculator;
import com.ericsson.uecontrol.gui.MainActivity;

/**
 * Created by ezivkoc on 2014-09-29.
 */
public class ExecNotification {
    private static final int NOTIFICATION_ID = 1;
    private static NotificationCompat.Builder mBuilder;

    public static void create(){
        mBuilder = createNotification();
        setNotification(mBuilder);
    }

    public static void update(double downThroughput, double upThroughput){
        if(mBuilder != null) {
            mBuilder.setContentTitle("Exec Behaviour: " + MainActivity.getExecutor().getRunningBehaviour().getName());
            mBuilder.setContentText(" Down: " + StringUtil.getBitThroughputString(downThroughput)
                    + " Up: " + StringUtil.getBitThroughputString(upThroughput));
            setNotification(mBuilder);
        }
    }

    public static void dismiss(){
        NotificationManager mNotificationManager =
                (NotificationManager) MainActivity.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(NOTIFICATION_ID);
        mBuilder = null;
    }


    private static NotificationCompat.Builder createNotification(){
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.getContext())
                .setSmallIcon(R.drawable.icon)
                .setContentTitle("UeControl Executing")
                .setContentText("Starting up...")
                .setOngoing(true);

        // Creates an explicit intent for an Activity in your app
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(MainActivity.getContext());
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(new Intent(MainActivity.getContext(), MainActivity.class));
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);

        return mBuilder;
    }

    private static void setNotification(NotificationCompat.Builder mBuilder){
        NotificationManager mNotificationManager =
                (NotificationManager) MainActivity.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }
}
