/* 
 * 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.gui;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.preference.DialogPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import de.avm.android.fritzapp.R;
import de.avm.android.fritzapp.com.ComSettingsChecker;
import de.avm.android.fritzapp.com.JasonBoxinfo;
import de.avm.android.fritzapp.com.discovery.BoxInfo;
import de.avm.android.fritzapp.service.BoxServiceConnection;
import de.avm.android.fritzapp.util.Clipboard;
import de.avm.android.tr064.net.Fingerprint;
import de.avm.fundamentals.activities.FeedbackActivityOld;
import de.avm.fundamentals.logger.FileLog;

/*
 * Activity to show info about connected box and to
 * open a browser with the FRITZ!Box configuration-menu
 */
public class OpenWebActivity extends PreferenceActivity implements OfflineActivity
{
	private static final String TAG = "OpenWebActivity";

    private OverflowMenuActivity.Delegate mOverflowMenuDelegate =
            new OverflowMenuActivity.Delegate(this);
	private ListView mPreferenceView;
	private View mNoInfoView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.boxinfo);
		mPreferenceView = (ListView)findViewById(android.R.id.list);
		mPreferenceView.setSelector(R.drawable.list_selector_background);
		mNoInfoView = findViewById(R.id.NoBoxinfoView);
	}

    @Override
    protected void onPostCreate(Bundle savedInstanceState)
    {
        super.onPostCreate(savedInstanceState);
        mOverflowMenuDelegate.onPostCreateActivity();
    }

    @Override
    public void invalidateOptionsMenu()
    {
        super.invalidateOptionsMenu();
        mOverflowMenuDelegate.invalidateOptionsMenu();
    }

	@Override
	protected void onResume()
	{
		super.onResume();
		if (!mBoxServiceConnection.bindService(getApplicationContext()))
			FileLog.w(TAG, "Failed to bind to BoxService.");
		updateDisplay(true);
	}

	@Override
	protected void onPause()
	{
		super.onPause();
		mBoxServiceConnection.unbindService();
	}
	
	private BoxServiceConnection mBoxServiceConnection = new BoxServiceConnection()
	{
		public void onComStatusChanged()
		{
			runOnUiThread(new Runnable()
			{
				public void run()
				{
					updateDisplay(true);
				}
			});
		}
	};

	private void updateDisplay(boolean reloadTam)
	{
		PreferenceScreen screen = getPreferenceManager()
				.createPreferenceScreen(this);
		screen.setPersistent(false);

		JasonBoxinfo jasonBoxInfo = ComSettingsChecker.getJasonBoxinfo();
		if (jasonBoxInfo == null)
		{
			mPreferenceView.setVisibility(View.GONE);
			mNoInfoView.setVisibility(View.VISIBLE);
			return;
		}
		mPreferenceView.setVisibility(View.VISIBLE);
		mNoInfoView.setVisibility(View.GONE);

		// category Box
		PreferenceCategory category = new PreferenceCategory(this);
		category.setTitle(getString(R.string.status_box));
		screen.addPreference(category);

		Preference preference = new DisplayPreference(this);
		preference.setTitle(R.string.boxinfo_name);
		preference.setSummary(jasonBoxInfo.getName());
		category.addPreference(preference);
		
		preference = new DisplayPreference(this);
		preference.setTitle(R.string.boxinfo_version);
		try { preference.setSummary(jasonBoxInfo.getVersion()); }
		catch(Exception e)
		{
            FileLog.w(TAG, e.getMessage(), e);
			preference.setSummary(R.string.unknown);
		}
		category.addPreference(preference);
		
		String lab = jasonBoxInfo.getLab();
		if (!TextUtils.isEmpty(lab))
		{
			preference = new DisplayPreference(this);
			preference.setTitle(R.string.boxinfo_lab);
			preference.setSummary(lab);
			category.addPreference(preference);
		}
		
		String locationIP = ComSettingsChecker.getLocationHost();
		// could not be a IPv6 address any more?
//			if (locationIP.indexOf(':') >= 0)
//			{
//				// IPv6 -> show IPv4 too
//				try
//				{
//					locationIP += "\n(" + 
//							InetAddressHelper.getByName(DataHub
//									.getFritzboxUrlWithoutProtocol(this))
//									.getHostAddress()
//							+ ")";
//				}
//				catch (Exception e)
//				{
//					FileLog.w(TAG, e.getMessage(), e);
//				}
//			}
		preference = new DisplayPreference(this);
		preference.setTitle(R.string.boxinfo_address);
		preference.setSummary(locationIP);
		category.addPreference(preference);

		final BoxInfo boxInfo = ComSettingsChecker.getBoxInfo();
		if ((boxInfo != null) && boxInfo.hasCertificateFingerprint())
		{
			// certificate's fingerprint
			category.addPreference(new CertificatePreference(this,
					boxInfo.getCertificateFingerprint()));
		}
		
		if ((boxInfo != null) && boxInfo.hasVoipCredentials())
		{
			// category phone
			category = new PreferenceCategory(this);
			category.setTitle(getString(R.string.status_sip));
			screen.addPreference(category);

			preference = new DisplayPreference(this);
			preference.setTitle(R.string.boxinfo_sip);
			preference.setSummary(boxInfo.getVoIPTitle());
			category.addPreference(preference);
			
			preference = new DisplayPreference(this);
			preference.setTitle(R.string.boxinfo_number);
			preference.setSummary(String.format(getString(
					R.string.boxinfo_number_fmt), boxInfo.getVoIPName()));
			category.addPreference(preference);
			
			// use currently available TAM info
			final String cachedTam = TamPreference.getCachedSelectedTam();
			if (!TextUtils.isEmpty(cachedTam))
			{
				Preference tamPreference = new DisplayPreference(this);
				tamPreference.setTitle(R.string.settings_tam);
				tamPreference.setSummary(cachedTam);
				category.addPreference(tamPreference);
			}

			// refresh TAM info?
			if (reloadTam)
			{
				TamPreference.getSelectedTam(this,
						new TamPreference.OnResultListener<String>()
				{
					public void onResult(String udn, final String result)
					{
						if (boxInfo.getUdn().equals(udn))
							runOnUiThread(new Runnable()
							{
								public void run()
								{
									if (!result.equals(cachedTam))
										updateDisplay(false);
								}
							});
					}

					public void onError(Exception error)
					{
						// ignore
					}
				});
			}
		}

		screen.bind(mPreferenceView);
		mPreferenceView.setAdapter(screen.getRootAdapter());
		setPreferenceScreen(screen);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
	    getMenuInflater().inflate(R.menu.boxinfo_menu, menu);
		return true;
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		menu.findItem(R.id.WebUI).setEnabled(
				!TextUtils.isEmpty(ComSettingsChecker.getLocationHost()));
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case R.id.WebUI:
				try
				{
					startActivity(new Intent(Intent.ACTION_VIEW, new Uri.Builder()
							.scheme("http")
							.encodedAuthority(ComSettingsChecker.getLocationHost())
							.build()));
				}
				catch(Exception exp)
				{ }
				break;
		
			case R.id.About:
				Help.showAbout(this);
				break;
				
			case R.id.Help:
				Help.showHelp(this);
				break;

            case R.id.action_feedback:
                startActivity(new Intent(this, FeedbackActivityOld.class));
                break;
		}
		return true;
	}
	
	private class CertificatePreference extends DialogPreference
	{
		public CertificatePreference(Context context, Fingerprint fingerprint)
		{
			super(context, (AttributeSet)null);

			setTitle(R.string.certificate_display);
			setSummary(R.string.certificate_fingerprint);
			setDialogTitle(R.string.certificate_fingerprint);
			setDialogMessage(fingerprint.toUserfriendlyString());
			setPositiveButtonText(android.R.string.copy);
		}

		@Override
		protected void onPrepareDialogBuilder(AlertDialog.Builder builder)
		{
			super.onPrepareDialogBuilder(builder);
		    builder.setCancelable(true)
					.setInverseBackgroundForced(true)
					.setNegativeButton(null, null);
		}

		@Override
	    protected void onDialogClosed(boolean positiveResult)
		{
            if (positiveResult)
            {
                Clipboard.create(getContext()).setPlainText(getDialogMessage());
                Toast.makeText(getContext(), R.string.copied_to_clipboard,
                        Toast.LENGTH_SHORT).show();
            }
	    }
	}
	
	public static Intent showIntent(Context context)
	{
		return new Intent(context, OpenWebActivity.class)
				.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	}
	
	public static Boolean canShow()
	{
		return ComSettingsChecker.getBoxInfo() != null;
	}
	
	public class DisplayPreference extends Preference
	{
		public DisplayPreference(Context context)
		{
			super(context);
			
			setShouldDisableView(false);
			setEnabled(false);
			setSelectable(false);
		}
	}
}