package org.r3pek.guiatv;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
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.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class ShowDay extends Activity {
	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 String day;
	private String channel;
	private ProgramList allPrograms; 
	
	private ListView lvProgDia;
	private TextView tvChannelname;
	private TextView tvDia;
	private Button btnNextDay;
	private Button btnPrevDay;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.channel_epg);
		
		long tmp = (Long) getIntent().getSerializableExtra("org.r3pek.guiatv.date");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        day = format.format(new Date(tmp));
		channel = (String) getIntent().getStringExtra("org.r3pek.guiatv.channel");
		
		lvProgDia = (ListView) findViewById(R.id.lvProgDia);
		tvChannelname = (TextView) findViewById(R.id.tvChannelName);
		tvDia = (TextView) findViewById(R.id.tvDia);
		btnNextDay = (Button) findViewById(R.id.btnNextDay);
		btnPrevDay = (Button) findViewById(R.id.btnPrevDay);
		
		btnNextDay.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
					Calendar c = Calendar.getInstance();
					c.setTime(format.parse(day));
					c.add(Calendar.DATE, 1);
					day = format.format(c.getTime());
				} catch (ParseException e) { }
				update();
			}
		});
		btnPrevDay.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
					Calendar c = Calendar.getInstance();
					c.setTime(format.parse(day));
					c.add(Calendar.DATE, -1);
					day = format.format(c.getTime());
				} catch (ParseException e) { }
				update();
			}
		});
		lvProgDia.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
		        Intent i = new Intent(getApplicationContext(), ProgramDetails.class);
		        i.putExtra("org.r3pek.guiatv.channel", channel);
		        i.putExtra("org.r3pek.guiatv.program", allPrograms.getPrograms().get(arg2));
		        i.putExtra("org.r3pek.guiatv.day", tvDia.getText());
		        startActivity(i);
			}
		});
		
		update();
	}
	
    @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() {
				allPrograms = new ProgramList(channel, day);
				SimpleDateFormat format = new SimpleDateFormat("HH:mm");
				SimpleDateFormat format_ori = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		        ArrayList<HashMap<String, String>> programs = new ArrayList<HashMap<String, String>>();
				if (allPrograms.getPrograms() != null && allPrograms.getProgramCount() > 0) {
					for (Program p : allPrograms.getPrograms()) {
						HashMap<String, String> channel = new HashMap<String, String>();
						channel.put("titulo", p.getTitle().trim());
						try {
							channel.put("hora", format.format(format_ori.parse(p.getStartHour())));
						} catch (Exception e) { };
						programs.add(channel);
					}
				} else {
					// Server Error
					HashMap<String, String> msg = new HashMap<String, String>();
					msg.put("titulo", "Erro");
					msg.put("hora", "00:00");
					programs.add(msg);
				}
		        
				/* Create the Adapter to show the information */
				final SimpleAdapter adap = new ProgramListSimpleAdapter(getApplicationContext(), programs, R.layout.epg_row,
					new String[] {"titulo", "hora"},
					new int[] {R.id.tvProgram, R.id.tvHour},
					allPrograms
				);
				
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						lvProgDia.setAdapter(adap);
						dismissDialog(DIALOG_PROGRESS);
					}
				});
			}
		};

		tvChannelname.setText((String) getIntent().getStringExtra("org.r3pek.guiatv.channelname"));
		tvDia.setText(day);
		
		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() {
								lvProgDia.setAdapter(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;
    	}
    }

}
