/* 
 * Copyright 2012 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.tr064.exceptions;

import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Locale;

import javax.net.ssl.SSLException;

import de.avm.android.tr064.R;

import android.content.Context;
import android.text.TextUtils;

/* Exception thrown on SSL problems. */
public class SslErrorException extends BaseException
{
	private static final long serialVersionUID = 5930264008537135850L;
	private static final String MESSAGE = "SSL error.";

	public static boolean isSslError(Exception e)
	{
		if (e != null)
		{
			Class<? extends Exception> cl = e.getClass();
			
			if (SSLException.class.equals(cl)) return true;
			if (SslErrorException.class.equals(cl)) return true;

			if (IOException.class.equals(cl))
			{
				String message = e.getMessage();
				if (!TextUtils.isEmpty(message) &&
						message.toLowerCase(Locale.getDefault()).contains("ssl"))
					return true;
			}
		}
		return false;
	}
	
	public static boolean isCertificateError(Exception e)
	{
		return getCertificateException(e) != null;
	}
	
	private static CertificateException getCertificateException(Exception e)
	{
		for (Throwable cause = e; cause != null; cause = cause.getCause())
			if (CertificateException.class.isAssignableFrom(cause.getClass()))
				return (CertificateException)cause;
		return null;
	}
	
	public static String getDisplayMessage(Context context, Exception e)
	{
		CertificateException exp = getCertificateException(e);
		if (exp != null) return exp.getMessage();
		return context.getString(R.string.ssl_exeption_message);
	}

	/**
	 * Instantiates a new data misformat exception.
	 * 
	 * @param string
	 *            the string
	 */
	public SslErrorException(String string)
	{
		super(string);
	}

	/**
	 * Instantiates a new data SSL error exception.
	 * 
	 * @param string
	 *            the string
	 * @param e
	 *            the e
	 */
	public SslErrorException(String string, Exception e)
	{
		super(MESSAGE, e);
	}

	/**
	 * Instantiates a new data SSL error exception.
	 * 
	 * @param e
	 *            the e
	 */
	public SslErrorException(Exception e)
	{
		super(MESSAGE, e);
	}
}