package com.dniemcu;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;

import com.dniemcu.PDFReceived.OnEventUpdateListener;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class DNIeMcu extends Activity implements OnEventUpdateListener {

	ArrayList<OperationItem> items = new ArrayList<OperationItem>();

    private boolean doubleBackToExitPressedOnce = false;
        private Context myContext;

	private SampleAdapter m_adapter;
	
	SharedPreferences sharedPreferences;
	private final static String SETTING_USER = "setting_user";
	
	private static final int NOTIFICACION_INBOX 	= 0;
	private static final int NOTIFICACION_SEND 		= 1;
	private static final int NOTIFICACION_CONFIGURE	= 2;

    class pdfFilter implements FilenameFilter {
        public boolean accept(File dir, String name) {
                return (name.endsWith(".pdf"));
        }
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Quitamos la barra del título
     	this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        
        // Indicamos que la aplicación ha empezado bien
        ((MyAppMcu)getApplicationContext()).setStarted(true);

        myContext = DNIeMcu.this;

        boolean bIsTabletSize= false;
        if ((getResources().getConfiguration().screenLayout & 
        	    Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) 
        {
        	 bIsTabletSize= true;
        }

        // Creamos el menú de opciones
        ListView listView = (ListView) findViewById(android.R.id.list);
        items.add(new OperationItem(((bIsTabletSize)? R.drawable.texto_entrada : R.drawable.red_texto_entrada),
						getString(R.string.op_abrirbuzon_desc),
						R.drawable.icono_buzon,
						((MyAppMcu)getApplicationContext()).getNotifications(MyAppMcu.EVENT_LOAD), true));
		items.add(new OperationItem(((bIsTabletSize)? R.drawable.texto_enviado : R.drawable.red_texto_enviado),
						getString(R.string.op_enviados_desc),	
						R.drawable.icono_enviados,	
						((MyAppMcu)getApplicationContext()).getNotifications(MyAppMcu.EVENT_SEND), false));
		items.add(new OperationItem(((bIsTabletSize)? R.drawable.texto_configuracion : R.drawable.red_texto_configuracion),
						getString(R.string.op_configure_desc),	
						R.drawable.icono_config,	
						((MyAppMcu)getApplicationContext()).getNotifications(MyAppMcu.EVENT_CONFIG), false));
        
        m_adapter = new SampleAdapter(getApplicationContext(), items);
        listView.setAdapter(m_adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        	@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) 
        	{    
        		//Creamos el Intent correspondiente
        		Intent intent;

        		switch(arg2)
        		{
	        		case NOTIFICACION_INBOX:
	    				intent = new Intent(DNIeMcu.this, PDFReceived.class);
                    	startActivityForResult(intent, 1);
	                	break;
        			case NOTIFICACION_SEND:
        				intent = new Intent(DNIeMcu.this, PDFSigned.class);
						startActivityForResult(intent, 1);
                    	break;
        			case NOTIFICACION_CONFIGURE:
        				intent = new Intent(DNIeMcu.this, MailConfiguration.class);
						startActivityForResult(intent, 1);
                    	break;
        		}
			}});
        
        RevisarNotificaciones();
    }

    @Override
    public void onBackPressed() {
        if (doubleBackToExitPressedOnce) {
            this.moveTaskToBack(true);
            return;
        }
        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(this, "Pulse de nuevo VOLVER para salir...", Toast.LENGTH_SHORT).show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                doubleBackToExitPressedOnce=false;
            }
        }, 2000);
    }
    
    private void RevisarNotificaciones()
    {
        File appDir;
        File backupDir;
        File inboxDir;
        File outboxDir;
        File sentDir;

    	boolean bMustDelete = false;
    	
    	try
    	{
    		// Si no hemos configurado la cuenta de correo, borramos todo (menos BACKUP)
    	    sharedPreferences = getApplicationContext().getSharedPreferences("com.sp.main_preferences", Context.MODE_PRIVATE);
    	    String user = sharedPreferences.getString(SETTING_USER,"");
    	    
    	    if(user.length()==0)
    	    {
    	    	((MyAppMcu)getApplicationContext()).setNotifications(MyAppMcu.EVENT_CONFIG, 1);
    	    	items.get(NOTIFICACION_CONFIGURE).setNotifications(1);
    	    	bMustDelete = true;
    	    }    	    
    	    
    	    appDir = getDir("FirmaPDF", MODE_PRIVATE);
		    if(!appDir.exists())
	    	    if(!appDir.mkdir())
	    	    {
	    	    	Toast.makeText(getApplicationContext(), "No se ha podido crear la carpeta:\n"+appDir, Toast.LENGTH_LONG).show();
	    	    	return;
	    	    }
		 
		    // Nos aseguramos de que exista el buzón de entrada
	    	inboxDir = new File(appDir, "Inbox"); 
	    	if((inboxDir.exists())&&(bMustDelete))
		    {
		    	String[] children = inboxDir.list();
		        for (int i = 0; i < children.length; i++) 
		            new File(inboxDir, children[i]).delete();
		    }
	    	
			if(!inboxDir.exists())
				if(!inboxDir.mkdir())
	    	    {
	    	    	Toast.makeText(getApplicationContext(), 
	    	    			"No se ha podido crear la carpeta:\n"+inboxDir.getAbsolutePath(), 
	    	    			Toast.LENGTH_LONG).show();
	    	    	return;
	    	    }
			
			// Nos aseguramos de que exista el buzón de salida
			outboxDir = new File(appDir, "Outbox"); 
			if((outboxDir.exists())&&(bMustDelete))
		    {
		    	String[] children = outboxDir.list();
		        for (int i = 0; i < children.length; i++) 
		            new File(outboxDir, children[i]).delete();
		    }
			
			if(!outboxDir.exists())
				if(!outboxDir.mkdir())
	    	    {
	    	    	Toast.makeText(getApplicationContext(), 
	    	    			"No se ha podido crear la carpeta:\n"+outboxDir.getAbsolutePath(), 
	    	    			Toast.LENGTH_LONG).show();
	    	    	return;
	    	    }
			
		    // Nos aseguramos de que exista el buzón de backup
		    backupDir = new File(appDir, "Backup"); 
			if(!backupDir.exists())
				if(!backupDir.mkdir())
	    	    {
	    	    	Toast.makeText(getApplicationContext(), 
	    	    			"No se ha podido crear la carpeta:\n"+backupDir.getAbsolutePath(), 
	    	    			Toast.LENGTH_LONG).show();
	    	    	return;
	    	    }
		   
			// Nos aseguramos de que exista el buzón de enviados
			sentDir = new File(appDir, "Enviados"); 
			if(!sentDir.exists())
				if(!sentDir.mkdir())
	    	    {
	    	    	Toast.makeText(getApplicationContext(), 
	    	    			"No se ha podido crear la carpeta:\n"+sentDir.getAbsolutePath(), 
	    	    			Toast.LENGTH_LONG).show();
	    	    	return;
	    	    }
		    
					
			// Comprobamos las notificaciones de documentos ENVIADOS
	    	((MyAppMcu)getApplicationContext()).setNotifications(MyAppMcu.EVENT_SEND,
	    			sentDir.listFiles(new pdfFilter()).length);
	    	items.get(NOTIFICACION_SEND).setNotifications(sentDir.listFiles(new pdfFilter()).length);
	    	
		    // Comprobamos las notificaciones de documentos RECIBIDOS
	    	((MyAppMcu)getApplicationContext()).setNotifications(MyAppMcu.EVENT_LOAD,
	    			inboxDir.listFiles(new pdfFilter()).length);
	    			items.get(NOTIFICACION_INBOX).setNotifications(inboxDir.listFiles(new pdfFilter()).length);
	    	
		    m_adapter.notifyDataSetChanged();
    	
    	} catch(Exception e)
    	{
    		Toast.makeText(getApplicationContext(), "No se han podido verificar notificaciones.\n"+e.getMessage(), Toast.LENGTH_LONG).show();
    		e.printStackTrace();
    	}
    }
    
    public class SampleAdapter extends ArrayAdapter<OperationItem> {
		private ArrayList<OperationItem> items;
		private LayoutInflater vi;
		
		public SampleAdapter(Context context,ArrayList<OperationItem> items) {
			super(context,0, items);
			this.items = items;
			vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;

			final OperationItem ei = items.get(position);
			if (ei != null)
			{
				v = vi.inflate(R.layout.list_item_row, parent, false);
				final TextView title = (TextView)v.findViewById(R.id.row_title);
				final TextView descr = (TextView)v.findViewById(R.id.row_description);
				final ImageView imgTitle = (ImageView)v.findViewById(R.id.row_iconText);
				final ImageView imgDnie = (ImageView)v.findViewById(R.id.row_dniesupport);
				final ImageView icon = (ImageView)v.findViewById(R.id.row_icon);
				TextView notif 	= (TextView)v.findViewById(R.id.row_notify);

                // Ajustamos el tipo de letra
                Typeface type = Typeface.createFromAsset(myContext.getAssets(),"fonts/NeutraText-LightAlt.otf");

				if(title != null) {
                    title.setText(ei.title);
                    title.setTypeface(type);
                }
				if(descr != null){
					descr.setText(ei.description);
                    descr.setTypeface(type);
                }
				if(icon != null)
					icon.setImageResource(ei.iconRes);
				if(imgTitle != null)
					imgTitle.setImageResource(ei.iconTexto);
				if(ei.supportsDnie)
					imgDnie.setVisibility(ImageView.VISIBLE);
				if(ei.getNotifications()!= 0) 
				{
					notif.setVisibility(ImageView.VISIBLE);
					notif.setText(String.valueOf(ei.getNotifications()));
				}
			}
			return v;
		}
	}

 	// Clase que define una OPERACIÖN
 	public class OperationItem {
 		public final String title;
 		public final String description;
 		private final int iconTexto;
 		private final int iconRes;
 		private int iNotif;
 		private final boolean supportsDnie;

 		public OperationItem(int iconTexto, String desc, int iconRes, int iNotif, boolean supportsDni) {
 			this.title 			= null;
 			this.iconTexto 		= iconTexto;
 			this.description 	= desc;
 			this.iconRes 		= iconRes;
 			this.iNotif 		= iNotif;
 			this.supportsDnie	= supportsDni;
 		}
 		
 		public int getNotifications(){
 			return iNotif;
 		}
 		
 		public void setNotifications(int iEvents){
 			iNotif = iEvents;
 		}
 	}

	@Override
	public void onEventUpdateListener(int iEvent, int[] iValue) {
		switch(iEvent)
		{
			case MyAppMcu.EVENT_LOAD:
				items.get(NOTIFICACION_INBOX).setNotifications(iValue[0]);
				break;
			case MyAppMcu.EVENT_SEND:
				items.get(NOTIFICACION_SEND).setNotifications(iValue[0]);
				break;
			case MyAppMcu.EVENT_CONFIG:
				items.get(NOTIFICACION_CONFIGURE).setNotifications(iValue[0]);
				break;
		}
		m_adapter.notifyDataSetChanged();
	} 	
}