package com.dniemcu;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

public class SplashScreen extends Activity {

	private static String TAG = SplashScreen.class.getName();

    private Context myContext;
	
	private String strError;
	private String newStatus;
	
	final Handler handler = new Handler();
	
	private TextView status;
	private String mail_user;
	private String mail_pass;
	
	final Runnable handleError = new Runnable() {
		public void run() 
		{
		   Toast.makeText(myContext, strError, Toast.LENGTH_LONG ).show();
		}
	};
	
	final Runnable updateStatus = new Runnable() {
		public void run() 
		{
			status.setText(newStatus);
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		try
		{
			this.requestWindowFeature(Window.FEATURE_NO_TITLE);
			
			// Ponemos en marcha el ProgressBar
			requestWindowFeature(Window.FEATURE_PROGRESS);
			setContentView(R.layout.splash);
	    	setProgressBarVisibility(true);

            myContext = this;

            // Ajustamos el tipo de letra
            Typeface fontType = Typeface.createFromAsset(myContext.getAssets(), "fonts/NeutraText-LightAlt.otf");
            TextView myText = (TextView)findViewById(R.id.splash_text_01);
            myText.setTypeface(fontType);
            myText = (TextView)findViewById(R.id.splash_text_02);
            myText.setTypeface(fontType);
            myText = (TextView)findViewById(R.id.splash_text_03);
            myText.setTypeface(fontType);
            myText = (TextView)findViewById(R.id.splash_text_04);
            myText.setTypeface(fontType);

            status= (TextView)this.findViewById(R.id.mailstatus);
            status.setTypeface(fontType);

			// Start timer and launch main activity
			IntentLauncher launcher = new IntentLauncher();
			launcher.start();
		} catch (Exception e){
            e.printStackTrace();
		}
	}
	
    public class IntentLauncher extends Thread {
	 
	 	SharedPreferences sharedPreferences;
		
		private final static String SETTING_USER = "setting_user";
		private final static String SETTING_PASS = "setting_pass";
		
	
	  @Override
	  /**
	   * Sleep for some time and than start new activity.
	   */
	  public void run() {
	     try 
	     {	    	
	    	//Las preferencias se guardarán en com.sp.main_preferences. Debes tenerlo en cuenta para cuando recuperes los valores
	 	    sharedPreferences = getApplicationContext().getSharedPreferences("com.sp.main_preferences", Context.MODE_PRIVATE);

	 	    //Recupera los valores de usuario y contraseña guardados en la actividad de SignUp
	 	    mail_user = sharedPreferences.getString(SETTING_USER,"");
	 	    mail_pass = sharedPreferences.getString(SETTING_PASS,"");
	 	    
	    	// Si no tenemos indicada cuenta de correo, lo avisamos 
	    	if(mail_user.length()==0)
	    	{
		 		newStatus = "Correo no indicado. Acceda al menú CONFIGURACIÓN";
			    handler.post(updateStatus);
                long SLEEP_TIME = 1;
                Thread.sleep(SLEEP_TIME *1000);
			}
	    	else
	    	{
		    	// Revisamos el correo
		    	newStatus = "Verificando correo...";
		    	handler.post(updateStatus);

                GMailReader mailServer = new GMailReader(mail_user, mail_pass);
                Message[] mails = mailServer.readMail();

                for(int idx=0; idx<mails.length;idx++)
                {
                    newStatus = "Comprobando mensaje...";
                    handler.post(updateStatus);

                    List<File> attachments = new ArrayList<File>();

                    Address []addrs = mails[idx].getFrom();
                    int idx2=0;
                    while(idx2<addrs.length)
                    {
						// Se comprueba si el email procede del colegio y contiene una notificación a firmar.
						// Para este ejemplo, incluir aquí un email que se reconozca como válido.
                        if(addrs[idx2].toString().contains("nombredelcolegio@madrid.org"))
                        {
                            newStatus = "Descargando notificaciones...";
                            handler.post(updateStatus);

                            // Obtenemos el adjunto
                            Multipart multipart = (Multipart) mails[idx].getContent();

                            for (int i = 0; i < multipart.getCount(); i++) {
                            BodyPart bodyPart = multipart.getBodyPart(i);
                            if((!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) &&
                                       (bodyPart.getFileName()==null)))
                              continue;

                            InputStream is = bodyPart.getInputStream();
                                File appDir = getDir("FirmaPDF", MODE_PRIVATE);
                            if(!appDir.exists())
                                appDir.mkdir();

                            File inboxDir = new File(appDir, "Inbox");
                            if(!inboxDir.exists())
                                if(!inboxDir.mkdir())
                                {
                                    Toast.makeText(getApplicationContext(),
                                            "No se ha podido crear la carpeta:\n"+inboxDir.getAbsolutePath(),
                                            Toast.LENGTH_LONG).show();
                                    return;
                                }

                            File f = new File(inboxDir.getPath() + "/"+bodyPart.getFileName());
                            FileOutputStream fos = new FileOutputStream(f);
                            byte[] buf = new byte[4096];
                            int bytesRead;
                            while((bytesRead = is.read(buf))!=-1) {
                                fos.write(buf, 0, bytesRead);
                            }
                            fos.close();
                            attachments.add(f);
                            }
                        }

                        idx2++;
                    }
                }
	    	}	 		
	     } catch (Exception e) {
			strError = "Error. No se ha podido comprobar el correo! \n"+e.getMessage();
			handler.post(handleError);
			Log.e(TAG, strError+e.getMessage());
			e.printStackTrace();
	     }
	     
	     Intent intent = new Intent(SplashScreen.this, DNIeMcu.class);
	     SplashScreen.this.startActivity(intent);
	     SplashScreen.this.finish();
	  }
 }
 
 public class GMailReader extends javax.mail.Authenticator { 
	    private String user; 
	    private String password; 
	    private Session session;
	    public GMailReader(String user, String password) { 
	        this.user = user; 
	        this.password = password; 
	        
	        try{		        
		        Properties props = new Properties();
			    props.put("mail.smtp.host", "smtp.gmail.com");
			    props.put("mail.smtp.socketFactory.port", "465");
			    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			    props.put("mail.smtp.auth", "true");
			    props.put("mail.smtp.port", "465");
			    session = Session.getDefaultInstance(props, new javax.mail.Authenticator() 
    		    {
    		        protected PasswordAuthentication getPasswordAuthentication() 
    		        {
    		        	return new PasswordAuthentication(mail_user, mail_pass);
    			    }
    		    });
		        ((MyAppMcu)getApplicationContext()).setSession(session);
	        }catch (Exception e)
	        {
	        	Log.e(TAG, "Error al abrir servidor de correo."+e.getMessage());
	        	e.printStackTrace();	        	
	        }
	        
	    } 
	    public synchronized Message[] readMail() throws Exception { 
	        try { 
	            Store store = session.getStore("imaps"); 
	            store.connect("smtp.gmail.com", user, password); 
	            Folder folder = store.getFolder("INBOX"); 
	            folder.open(Folder.READ_ONLY); 
	            
	            int numMax = folder.getMessageCount();
	            int numFrom = 1; 
	            if(numMax>15)
	            	numFrom = folder.getMessageCount()-15;
	            
	            Message[] msgs = folder.getMessages(numFrom, numMax); 
	            FetchProfile fp = new FetchProfile(); 
	            fp.add(FetchProfile.Item.ENVELOPE);
	            folder.fetch(msgs, fp);  
	            
	            return msgs; 
	        } catch (Exception e) { 
	            Log.e("readMail", e.getMessage(), e); 
	        	e.printStackTrace();
	            return null; 
	        } 
	    } 
	}
}