package org.r3pek.guiatv;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class GuiaTV extends ListActivity {
	private final int DIALOG_PROGRESS = 0;
	private final int DIALOG_ABOUT = 1;
	
	private final int MENU_REFRESH = 0;
	private final int MENU_ABOUT = 1;
	
	private ChannelList allChannels;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        getListView().setTextFilterEnabled(true);
       	update();
    }
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        TextView tv = (TextView) v.findViewById(R.id.tvNome);
        int pos = allChannels.namePos(tv.getText().toString());
        Intent i = new Intent(getApplicationContext(), ShowDay.class);
        i.putExtra("org.r3pek.guiatv.date", System.currentTimeMillis());
        i.putExtra("org.r3pek.guiatv.channel", allChannels.getChannels().get(pos).getSigla());
        i.putExtra("org.r3pek.guiatv.channelname", allChannels.getChannels().get(pos).getName());
        startActivity(i);
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
      super.onConfigurationChanged(newConfig);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, MENU_REFRESH, 0, "Actualizar").setIcon(android.R.drawable.ic_menu_rotate);
        menu.add(0, MENU_ABOUT, 0, "Acerca").setIcon(android.R.drawable.ic_menu_info_details);;
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_REFRESH:
            update();
            return true;
        case MENU_ABOUT:
        	showDialog(DIALOG_ABOUT);
        	return true;
        }
        return false;
    }
    
    private void update() {
    	Runnable r = new Runnable() {
			@Override
			public void run() {
		        allChannels = new ChannelList();
		        ArrayList<HashMap<String, String>> channels = new ArrayList<HashMap<String, String>>();
				if (allChannels.getChannels() != null && allChannels.getChannelCount() > 0) {
					for (Channel c : allChannels.getChannels()) {
						HashMap<String, String> channel = new HashMap<String, String>();
						channel.put("nome", c.getName().trim());
						channels.add(channel);
					}
				} else {
					// Server Error
					HashMap<String, String> msg = new HashMap<String, String>();
					msg.put("nome", "Erro");
					channels.add(msg);
				}
		        
				/* Create the Adapter to show the information */
				final SimpleAdapter adap = new ChannelsSimpleAdapter(getApplicationContext(), channels, R.layout.main_row,
					new String[] {"nome"},
					new int[] {R.id.tvNome},
					allChannels
				);

				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						setListAdapter(adap);
				        dismissDialog(DIALOG_PROGRESS);
					}
				});
			}
		};
        showDialog(DIALOG_PROGRESS);
		Thread t = new Thread(r);
		t.start();
    }

    @Override
    public Dialog onCreateDialog(int id) {
    	switch (id) {
    		case DIALOG_PROGRESS: {
    			ProgressDialog d = new ProgressDialog(this);
    			d.setCancelable(true);
    			d.setMessage("Aguarde...");
    			d.setOnCancelListener(new OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						HashMap<String, String> msg = new HashMap<String, String>();
						ArrayList<HashMap<String, String>> a_msg = new ArrayList<HashMap<String, String>>();
						a_msg.add(msg);
						msg.put("nome", "Cancelado");
						final SimpleAdapter adap = new SimpleAdapter(getApplicationContext(), a_msg, R.layout.main_row,
								new String[] {"msg"},
								new int[] {R.id.tvNome}
							);

						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								setListAdapter(adap);
							}
						});
					}
				});
    			
    			return d;
    		}
    		case DIALOG_ABOUT: {
    			Dialog d;
    			LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
    			View layout = inflater.inflate(R.layout.about, (ViewGroup)findViewById(R.id.aboutRoot));
    			ImageView image = (ImageView)layout.findViewById(R.id.ImageView01);
    			image.setImageResource(R.drawable.icon);
    			Builder builder = new AlertDialog.Builder(this);
    			builder.setView(layout);
    			d = builder.create();
    			return d;
    		}
    		default: return null;
    	}
    }

}