package org.arkiwi.app.utility;

import java.io.InputStream;
import java.net.URL;
import java.text.DecimalFormat;

import org.arkiwi.app.R;
import org.arkiwi.app.activity.ATab;
import org.arkiwi.app.feed.FeedItem;
import org.arkiwi.app.feed.FeedItemFile;
import org.arkiwi.app.feed.FeedQuery;
import org.arkiwi.app.interfaces.Define;
import org.arkiwi.app.interfaces.SDialogInterface;

import io.vov.vitamio.VitamioInstaller;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.Settings;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.AbsListView.LayoutParams;

public class SDialog implements SDialogInterface, Define {
	private final static String LOG_TAG = "SDialog"; 
	private static Dialog mDialog;
	
	public static void spinnerDialog(Activity caller, int title, int msg) {
		Resources res = caller.getResources();
		
		mDialog = new ProgressDialog(caller,ProgressDialog.STYLE_SPINNER);
		mDialog.setTitle(title);//"HTTP Connection"
		((ProgressDialog) mDialog).setMessage(res.getString(msg));//"Connecting..."
		((ProgressDialog) mDialog).setIndeterminate(true);
		mDialog.show();
	}
	
	public static Dialog neutralDialog(Activity caller, final int ID, int title, int icon, View view){
		Resources res = caller.getResources();
		
		mDialog = new AlertDialog.Builder(caller).create();
		mDialog.setTitle(res.getString(title));
		((AlertDialog) mDialog).setIcon(res.getDrawable(icon));
		((AlertDialog) mDialog).setButton(Dialog.BUTTON_NEUTRAL, "Ok",
				new Dialog.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (ID) {
							default:
								removeDialog();
								break;
						}
					}
				});
		
		if (view != null)
			((AlertDialog) mDialog).setView(view);
			
		return mDialog;
	}
	
	public static Dialog choseDialog(final Activity caller, final int ID, int title, int icon, int yesmsg, int nomsg, View view){
		Resources res = caller.getResources();
		
		mDialog = new AlertDialog.Builder(caller).create();
		((AlertDialog) mDialog).setTitle(title);
		((AlertDialog) mDialog).setIcon(icon);

		((AlertDialog) mDialog).setButton(res.getString(yesmsg),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface d, int which) {
		                Uri marketUri = Uri.parse(URI_GEN_MARKET
		                        + VitamioInstaller.getCompatiblePackage());
		                Intent marketIntent = new Intent(Intent.ACTION_VIEW,
		                        marketUri);
						switch (ID) {
							case DIALOG_VITAMIO_NOTF:
								caller.startActivity(marketIntent);
								dismissDialog();
								break;
							case DIALOG_VITAMIO_COMPATIBLE:
								caller.startActivity(marketIntent);
			            	    dismissDialog();
								break;
							case DIALOG_WIFI:
								caller.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
								//senza il return al ritorno dall'intent si chiude l'app
								return;
							case DIALOG_CLOSE:
								caller.stopService(ATab.feedBurnI);
								dismissDialog();
								caller.finish();
							default:
								dismissDialog();
								break;
						}
					}
				});
		((AlertDialog) mDialog).setButton2(res.getString(nomsg),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface d, int which) {
						dismissDialog();
					}
				});
		
		if (view != null)
			((AlertDialog) mDialog).setView(view);

		return mDialog;
	}
	
	public static Dialog showMetaDialog(Activity caller, FeedItem f) {
		ScrollView sv = new ScrollView(caller);
		LinearLayout l = new LinearLayout(caller);
		setScrollV(sv, l);

		String type = f.getMediaType();
		l.addView(setMetaTV(caller, R.string.diag_meta_titolo, true));
		l.addView(setMetaTV(caller, f.getTitle(), false));
		l.addView(setMetaTV(caller, R.string.diag_meta_tipo, true));
		l.addView(setMetaTV(caller, type, false));
		l.addView(setMetaTV(caller, R.string.diag_meta_pubDate, true));
		l.addView(setMetaTV(caller, f.getPubDate(), false));
		l.addView(setMetaTV(caller, R.string.diag_meta_desc, true));
		l.addView(setMetaTV(caller, f.getDescriprion(), false));
		
		if (! type.equalsIgnoreCase(caller.getString(R.string.rss_type_dir))) {
			DecimalFormat dtime = new DecimalFormat("#.##");

			l.addView(setMetaTV(caller, R.string.diag_meta_f_creator, true));
			l.addView(setMetaTV(caller, ((FeedItemFile) f).getCreator(), false));
			
			l.addView(setMetaTV(caller, R.string.diag_meta_f_tag, true));
			l.addView(setMetaTV(caller, ((FeedItemFile) f).getTags(), false));
			
			l.addView(setMetaTV(caller, R.string.diag_meta_f_duration, true));
			double duration = Double.valueOf(((FeedItemFile) f).getDuration()) / 60;
			l.addView(setMetaTV(caller, dtime.format(duration) + " minuti"  , false));
			
			l.addView(setMetaTV(caller, R.string.diag_meta_f_size, true));
			double size = Double.valueOf(((FeedItemFile) f).getSize()) / 1024 / 1024;
			l.addView(setMetaTV(caller, dtime.format(size) + " Mbyte", false));
			
			l.addView(setMetaTV(caller, R.string.diag_meta_f_channels, true));
			l.addView(setMetaTV(caller, ((FeedItemFile) f).getChannels(), false));
			l.addView(setMetaTV(caller, R.string.diag_meta_f_rate, true));
			l.addView(setMetaTV(caller, ((FeedItemFile) f).getRate() + " Mhz", false));
		}
		
		return (AlertDialog) neutralDialog(caller, DIALOG_META, R.string.diag_meta_title, R.drawable.ic_dialog_metadata, sv);
	}
	
	public static Dialog showQRDialog(Activity caller, String qrcode_url) {
			ImageView iv = new ImageView(caller);
			try {
				URL url = new URL(qrcode_url);
				InputStream content = (InputStream) url.getContent();
				Drawable d = Drawable.createFromStream(content, "src");
				iv.setImageDrawable(d);
			} catch (Exception e) {
				e.getStackTrace();
			}
			
			return (AlertDialog) SDialog.neutralDialog(caller, DIALOG_QR, R.string.diag_act_QR, R.drawable.qr, iv);		
	}
	
	public static Dialog moreiDialog(Activity caller, FeedQuery q){		
		ScrollView sv = new ScrollView(caller);
		LinearLayout l = new LinearLayout(caller);
		setScrollV(sv,l);
		
		//TODO: for (.. lista ..) { l.addView(SDialog.setMetaDialogText(c, lista(i), true)); }
		l.addView(setMetaTV(caller, R.string.diag_morei_qid, true));
		l.addView(setMetaTV(caller, String.valueOf(q.getQid()), false));
		l.addView(setMetaTV(caller, R.string.diag_morei_feed_title, true));
		l.addView(setMetaTV(caller, q.getTitle(), false));
		l.addView(setMetaTV(caller, R.string.diag_morei_desc, true));
		l.addView(setMetaTV(caller, q.getDesc(), false));
		l.addView(setMetaTV(caller, R.string.diag_morei_last, true));
		l.addView(setMetaTV(caller, q.getLast(), false));
		l.addView(setMetaTV(caller, R.string.diag_morei_refresh, true));
		l.addView(setMetaTV(caller, q.getRefresh(), false));
		l.addView(setMetaTV(caller, R.string.diag_morei_link, true));
		l.addView(setMetaTV(caller, q.getLink(), false));
		
		 return (AlertDialog) SDialog.neutralDialog(caller, DIALOG_MOREI, R.string.diag_morei_title, R.drawable.morei, sv);
	}
	
	public static Dialog vitamioDialog(Activity caller, int type){
		int title = R.string.diag_vitamio_notc_title,
			icon = R.drawable.gplay,
			yes = R.string.diag_vitamio_notc_yesmsg,
			no = R.string.diag_vitamio_notc_nomsg,
			msg = R.string.diag_vitamio_notc_msg;

		if( type == DIALOG_VITAMIO_NOTF) {
			title = R.string.diag_vitamio_notf_title;
			yes = R.string.diag_vitamio_notf_yesmsg;
			no = R.string.diag_vitamio_notf_nomsg;
			msg = R.string.diag_vitamio_notf_msg;
		}
		
		return (AlertDialog) choseDialog(caller, type, title, icon, 
						yes, no, setHtmlTV(caller, msg));
	}
	
	public static TextView setSimpleTV(Context c, int msg) {
		TextView t = new TextView(c);
		t.setGravity(Gravity.CENTER_HORIZONTAL);
		t.setPadding(3, 16, 3, 16);
		t.setText(msg);

		return t;
	}
	//per setMetaTV e setHtmlTV il Context deve essere this dell'activity 
	//e non getAppContext o getBaseContext pena Err: startActivity from outside an Activity Context...
	private static TextView setMetaTV(Context c, int txt, boolean desc) {
		return setMetaTV(c, c.getString(txt), desc);
	}
	
	private static TextView setMetaTV(Context c, String txt, boolean desc) {
		int textSize = 8;
		TextView t = new TextView(c);
		t.setText(txt);
		if (desc) {
			t.setTextColor(Color.WHITE);
			t.setPadding(8, 0, 0, 0);
		} else {
			t.setPadding(2, 0, 2, 1);
			Linkify.addLinks(t, Linkify.WEB_URLS);
			textSize = 12;
		}

		t.setTextSize(textSize);

		return t;
	}

	public static TextView setHtmlTV(Context c, int txt) {
		TextView t = new TextView(c);
		t.setMovementMethod(LinkMovementMethod.getInstance());
		t.setLinksClickable(true);
		t.setText(Html.fromHtml(c.getString(txt)));
		t.setPadding(5, 5, 5, 5);
		t.setClickable(false);
		t.setLongClickable(false);
		return t;
	}
	
	private static void setScrollV(ScrollView sv, LinearLayout l){
		sv.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		l.setOrientation(LinearLayout.VERTICAL);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		lp.setMargins(100, 0, 100, 0);
		sv.addView(l, lp);
	}

	private static void removeDialog() {
		Log.i(LOG_TAG, "removeDg()");
	    if (mDialog != null)
	        mDialog.cancel();
	}

	public static void dismissDialog() {
	    if (mDialog != null)
	        mDialog.dismiss();
	}
}
