/* 
 * Copyright 2015 by AVM GmbH <info@avm.de>
 *
 * This software contains free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License ("License") as 
 * published by the Free Software Foundation  (version 3 of the License). 
 * This software is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the copy of the 
 * License you received along with this software for more details.
 */

package de.avm.android.fritzapp.service;

import de.avm.android.fritzapp.R;
import de.avm.android.fritzapp.com.ComSettingsChecker;
import de.avm.android.fritzapp.com.discovery.BoxInfo;
import de.avm.android.fritzapp.gui.FRITZApp;
import de.avm.android.fritzapp.gui.SettingsActivity;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.app.NotificationCompat;

/**
 * Manager for connection status notifications
 */
public class ComStatus
{
	public static final int ID = 1;

	private Service mService;
	private Notification mNotification = null;

	// last notified
	private String mUdn = "";
	private boolean mHasError = false;
	private int mSipState = ComSettingsChecker.SIP_NOTREGISTERED;

	public ComStatus(Service service)
	{
		mService = service;
	}
	
	/**
	 * Referesh notification to reflect status changes
	 *
	 * @return true if there where changes
	 */
	public boolean refresh()
	{
		BoxInfo boxInfo = ComSettingsChecker.getBoxInfo();
		String udn = (boxInfo == null) ? "" : boxInfo.getUdn();
        if (udn == null) udn = "";
		boolean hasError = ComSettingsChecker.getLastError().isError();
		int sipState = ComSettingsChecker.getSipState();
		if ((!mUdn.equals(udn)) || (hasError != mHasError) || (sipState != mSipState))
		{
			mUdn = udn;
			mHasError = hasError;
			mSipState = sipState;
			update();
			return true;
		}
        return false;
	}

    /**
     * Referesh notification to reflect visibility option changes
     */
    public void refreshDisplay()
    {
        update();
    }
	
	/**
	 * Remove notification
	 */
	public void clear()
	{
		mUdn = "";
		mHasError = false;
		mSipState = ComSettingsChecker.SIP_NOTREGISTERED;
		stopForeground();
	}

    @SuppressLint("InlinedApi")
    private void update()
	{
		if (!ComSettingsChecker.isConnected())
		{
			stopForeground();
			return;
		}

        NotificationCompat.Builder  builder = new NotificationCompat.Builder(mService)
                .setContentTitle(mService.getString(R.string.app_name))
                .setTicker(mService.getString(R.string.connection_on))
                .setOngoing(true)
                .setWhen(0).setShowWhen(false)
                .setCategory(Notification.CATEGORY_SERVICE)
                .setVisibility(Notification.VISIBILITY_SECRET)
                .setContentIntent(PendingIntent.getActivity(mService, 0, new Intent(mService,
                        FRITZApp.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0));
        if (SettingsActivity.isCautiousNotification(mService))
            builder.setPriority(Notification.PRIORITY_MIN);

		switch (mSipState)
		{
			case ComSettingsChecker.SIP_AWAY:
                builder.setSmallIcon(R.drawable.ic_stat_notify_fon_off)
                        .setLights(Color.RED, 125, 2875) // red LED flashing
                        .setContentText(mService.getString(R.string.regfailed));
				break;
				
			case ComSettingsChecker.SIP_IDLE:
                builder.setSmallIcon(R.drawable.ic_stat_notify_fon_off)
                        .setContentText(mService.getString(R.string.reg));
				break;
				
			case ComSettingsChecker.SIP_AVAILABLE:
                builder.setSmallIcon(R.drawable.ic_stat_notify_fon_on)
                        .setContentText(mService.getString(R.string.regok));
				break;

			case ComSettingsChecker.SIP_NOTREGISTERED:
			default:
                builder.setSmallIcon(R.drawable.ic_stat_notify_fon_off)
                        .setContentText(mService.getString(R.string.regno));
				break;
		}
		
        if (mNotification == null)
        {
            mNotification = builder.build();
            mService.startForeground(ID, mNotification);
        }
        else
        {
            mNotification = builder.build();
            ((NotificationManager)mService.getSystemService(Context.NOTIFICATION_SERVICE))
                    .notify(ID, mNotification);
        }
	}

	private void stopForeground()
	{
		if (mNotification == null) return;

		mService.stopForeground(true);
		mNotification = null;
	}
}
