package com.dniemcu;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.dniemcu.gui.CustomPdfAdapter;
import com.dniemcu.gui.MyPasswordDialog;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.security.DigestAlgorithms;
import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;

import de.tsenger.androsmex.data.CANSpecDO;
import de.tsenger.androsmex.data.CANSpecDOStore;

import es.gob.jmulticard.card.dnie.FakeX509Certificate;
import es.gob.jmulticard.jse.provider.DnieProvider;
import es.gob.jmulticard.ui.passwordcallback.CancelledOperationException;
import es.gob.jmulticard.ui.passwordcallback.DNIeDialogManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Parcelable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class PrKOperations extends Activity {
	
	private String m_PDFinbox;
	private String m_PDFoutbox;
	private String m_PDFsendbox;
	
	private KeyStore keyStoreDNIe;

	final Handler myHandler = new Handler();
	private String strError;

	private NfcA exNfcA;
	private NfcB exNfcB;
	private IsoDep exIsoDep;
	private Tag tagFromIntent;
	
	private CANSpecDOStore cansDO;
	private CANSpecDO canDnie;

	private ProgressDialog progressBar;
	private String textoProcessDlg;
	
	private ArrayList<PDFSigned.PDFItem> pdfItems = new ArrayList<PDFSigned.PDFItem>();
	List<String> filesPDF = new ArrayList<String>();
	private ListView listView;

	private Context myContext;
	private static final String TAG = "PrKOperations: ";

    Typeface fontType;

	private static int PDF_VIEWER = 0x10;
    
    private boolean m_success = false;
    private boolean m_bRestart = false;
    
    SharedPreferences sharedPreferences;
	private final static String SETTING_USER = "setting_user";
	private final static String SETTING_PASS = "setting_pass";
	
    private File pdfFile;
    private File appDir;
    private File sentDir;
    private File temporalFile; 

    // Dirección de envío del documento firmado. Debería ser la del colegio origen
	private String m_destino = "direccionemail@mail.com";

    final Runnable updateStatus = new Runnable() {
		public void run() 
		{
			progressBar.setMessage(textoProcessDlg);
			progressBar.show();
		}
	};
	
	final Runnable updateResult = new Runnable()
	{
		public void run() 
		{
    		if(!m_success)
    		{    			
    			((TextView)findViewById(R.id.result1)).setText(R.string.str_envio_error);
    			findViewById(R.id.result1).setVisibility(TextView.VISIBLE);
    			((TextView)findViewById(R.id.result2)).setText(R.string.str_envio_error2);
    			findViewById(R.id.result2).setVisibility(TextView.VISIBLE);
    			((ImageView)findViewById(R.id.resultimg)).setImageResource(R.drawable.checked_false);
    			findViewById(R.id.resultimg).setVisibility(ImageView.VISIBLE);
    			
    			// Mostramos el error
    			TextView txtFinal = (TextView)findViewById(R.id.resultinfo);
            	
            	DisplayMetrics metrics;
            	metrics = getApplicationContext().getResources().getDisplayMetrics();
            	txtFinal.setTextSize(txtFinal.getTextSize()/metrics.density);
            	txtFinal.setText(strError);
            	txtFinal.setVisibility(TextView.VISIBLE);
				return;
    		}
    		
    		// La operación se realizó correctamente. Lo indicamos
			((TextView)findViewById(R.id.result1)).setText(R.string.str_envio_correcto);
			findViewById(R.id.result1).setVisibility(TextView.VISIBLE);
			((TextView)findViewById(R.id.result2)).setText(R.string.str_envio_correcto3);
			findViewById(R.id.result2).setVisibility(TextView.VISIBLE);
			((ImageView)findViewById(R.id.resultimg)).setImageResource(R.drawable.checked_true);
			findViewById(R.id.resultimg).setVisibility(ImageView.VISIBLE);
			((TextView)findViewById(R.id.resultinfo)).setText(R.string.str_mostrar_pdf);
			findViewById(R.id.resultinfo).setVisibility(TextView.VISIBLE);
        	
			// Mostramos la lista de ficheros enviados s�lo si la operaci�n fue correcta, claro
    	    pdfFile = new File(m_PDFsendbox);
    	    if(pdfFile.exists())
    	    {
    	    	PDFSigned pdfLisIt = new PDFSigned();
    	    	String fechado = new SimpleDateFormat("dd-MM-yyyy, HH:mm:ss").format(new Date(pdfFile.lastModified()));
    	    	
    	    	Bitmap signedIcon = BitmapFactory.decodeResource(getResources(), R.drawable.pdf_signed2);
    			pdfItems.add(pdfLisIt.new PDFItem(signedIcon, pdfFile.getName(), "Enviado: "+fechado, (pdfFile.length()/1024)+" Kbs"));
            	filesPDF.add(pdfFile.getName());
            	
            	findViewById(R.id.resultinfo).setVisibility(TextView.VISIBLE);
            	findViewById(R.id.resultlist).setVisibility(LinearLayout.VISIBLE);

                CustomPdfAdapter mAdapter = new CustomPdfAdapter(myContext, m_PDFsendbox, R.id.list, pdfItems);
    		    listView.setAdapter(mAdapter);
    		    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    	        	@Override
    				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) 
    	        	{
    	        		// Aseguramos el acceso a los directorios necesarios
    	    			appDir = getDir("FirmaPDF", MODE_PRIVATE);
    	    			sentDir = new File(appDir, "Enviados"); 
    	    			if(!sentDir.exists())
    	    				sentDir.mkdir();
    	    			
    					String fileName= sentDir.getPath()+"/"+pdfItems.get(arg2).getFileName();
    					
    					try {
    						// Creamos el fichero temporal
    						temporalFile = File.createTempFile("temp", ".pdf", Environment.getExternalStorageDirectory());
    						
    						// Copiamos el contenido
    						InputStream in = new FileInputStream(new File(fileName));
    					    OutputStream out = new FileOutputStream(temporalFile);
    					    byte[] buf = new byte[1024];
    					    int len;
    					    while ((len = in.read(buf)) > 0) {
    					        out.write(buf, 0, len);}
    					    in.close();
    					    out.close();
    					    
    						// Abrimos el nuevo PDF
    						Uri path = Uri.fromFile(temporalFile); 
    						Intent intent = new Intent(Intent.ACTION_VIEW);
    						intent.setDataAndType(path, "application/pdf");
    						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    		            	startActivityForResult(intent, PDF_VIEWER);
    	            	} catch (IOException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
    				}});
    		    mAdapter.notifyDataSetChanged();
    	    }
		}	
	};


	@Override
	protected void onStart() {
		super.onStart();
		
		// Activamos la activity ENABLE = true
    	PackageManager packman = getApplicationContext().getPackageManager();
    	ComponentName componentName = new ComponentName(getApplicationContext(), PrKOperations.class);
    	packman.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);//*/
		
		if(m_bRestart)
		{
			// Si no hemos abierto correctamente, salimos
	        if(!((MyAppMcu)getApplicationContext()).isStarted())
	        {
	        	Toast.makeText(getApplicationContext(), "Esta aplicación había quedado abierta irregularmente. Salimos.\n", Toast.LENGTH_SHORT).show();
	    			      
	        	android.os.Process.killProcess(android.os.Process.myPid());
		     	System.exit(0);
		     	
	        	return;
	        }
			
			if(tagFromIntent==null)
			{
				Toast.makeText(getApplicationContext(), "No hay disponible ningún dispositivo NFC.", Toast.LENGTH_SHORT).show();
				return;
			}
					        	
			// Si est� disponible alg�n interfaz v�lido, lanzamos la tarea
	    	if( (exNfcA!=null) || (exNfcB!=null) || (exIsoDep!=null) )
    		{
    			MyTaskDNIe newTask = new MyTaskDNIe();
    			newTask.execute();
    		}
		}
	}    
            
	public class MyTaskDNIe extends AsyncTask<Void, Integer, Void>
	{	
	    @Override        
	    protected void onPreExecute() 
	    { 
	    	// Lanzamos el diálogo con el progreso
		    progressBar = new ProgressDialog(PrKOperations.this);
		    progressBar.setIndeterminate(true);
		    progressBar.setCancelable(false);
		    progressBar.setTitle("DNIe version 3.0");
		    progressBar.setMessage("Estableciendo conexión...");
		    progressBar.show();
	    }
	    
		@Override
	    protected Void doInBackground(Void... arg0) 
		{
			try 
			{
				// Paso 1: accedemos al certificado de firma del DNIe
				CargarCDF();
			}
			catch (Exception e) 
			{	    			
	    		strError = "Ocurrió un error durante la lectura y parseo de DFs.\n"+ e.getMessage();
	    		Log.e(TAG, "doInBackground MyTaskDNIe\n" + e.getMessage());
		        return null;
			}
			
			try 
			{
				// Paso 2: firmamos el documento PDF
				FirmarPDF();
			} 
			catch (Exception e) 
			{	    			
	    		strError = "Ocurrió un error durante el proceso de firma.\n"+ e.getMessage();
	    		Log.e(TAG, "doInBackground MyTaskDNIe\n" + e.getMessage());
		        return null;
			}

			try 
			{
	        	// Paso 3: env�o del PDF
				EnviarPDF();
				
				strError = "Envío de documento realizado CORRECTAMENTE.";
				m_success = true;
			} 
			catch (Exception e) 
			{	    			
	    		strError = "Ocurrió un error durante el envío del documento.\n"+ e.getMessage();
	    		Log.e(TAG, "doInBackground MyTaskDNIe\n" + e.getMessage());
				return null;
			}
            
			return null;
        }

	    @Override
	    protected void onPostExecute(Void result) 
	    { 
	    	// Cerramos el diálogo de progreso y terminamos
    		progressBar.dismiss();
    		
    		// Limpiamos el keystore
    		keyStoreDNIe = null;
    		
    		// Mostramos el resultado final y terminamos    		
    		myHandler.post(updateResult);
        }
    }
    
    private PdfSignatureAppearance PDF_Firmar(KeyStore ksUserDNIe) throws Exception
    {		
    	PdfSignatureAppearance appearance;
    			
    	try
		{        	
    		// Dejamos indicado el diálogo usado para solicitar el PIN
        	MyPasswordDialog myFragment = new MyPasswordDialog(PrKOperations.this, true);
        	DNIeDialogManager.setDialogUIHandler(myFragment);
			
            Enumeration<String> aliases = ksUserDNIe.aliases();
            while (aliases.hasMoreElements()){
                String aliasPDF = aliases.nextElement();
                if (ksUserDNIe.isCertificateEntry(aliasPDF)){
                    if (aliasPDF.toLowerCase().contains("firma")){
                        PrivateKey key = (PrivateKey)ksUserDNIe.getKey(aliasPDF, null);
                        Certificate[] chain = ksUserDNIe.getCertificateChain(aliasPDF);
                        
                        InputStream ims = getAssets().open("pdf_signed2.png");
                        Bitmap bmp = BitmapFactory.decodeStream(ims);
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
                        
                        PDFSignature metasign = new PDFSignature();
                        appearance = metasign.sign(	null, m_PDFinbox, m_PDFoutbox,
                                                    chain, key, DigestAlgorithms.SHA1,
                                                    "DNIeJCAProvider", CryptoStandard.CMS,
                                                    "Autorización/Otorgamiento de representación", "");

                        return appearance;
                    }
               }
            }
        }catch (CancelledOperationException e){ 
        	handleError("La operación de firma ha sido cancelada.\n"+e.getMessage());
			borrarFichero(m_PDFoutbox);
			e.printStackTrace();
            throw e;
        }catch (IOException e) {
			handleError("Error de IO al realizar la firma electrónica con el DNIe.\n"+e.getMessage());
			borrarFichero(m_PDFoutbox);
			e.printStackTrace();
			throw e;
		} catch (GeneralSecurityException e){
			handleError("Error de seguridad al realizar la firma electrónica con el DNIe.\n"+e.getMessage());
			borrarFichero(m_PDFoutbox);
			e.printStackTrace();
			throw e;
		} catch(DocumentException e){
			handleError("No se ha podido realizar la firma electrónica del documento.\n"+e.getMessage());
			borrarFichero(m_PDFoutbox);
			e.printStackTrace();
			throw e;
		} catch (Exception e) {
			handleError("No se ha podido realizar ninguna firma con el DNIe.\n"+e.getMessage());
			borrarFichero(m_PDFoutbox);
			e.printStackTrace();
			throw e;
		}
    	
    	return null;
    }
        
    private void handleError(String str)
    {
    	strError = str;
    	myHandler.post(updateResult);
    }
    
    private boolean borrarFichero(String fichero)  
    {
    	File file = new File(fichero);
    	if(file.exists())
    		return file.delete();

        return true;
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {

			// volvemos al Activity principal
			Intent 	intent = new Intent(PrKOperations.this, DNIeMcu.class);
			startActivity(intent);
	        return false;
        }
        else
        	return super.onKeyDown(keyCode, event);
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Quitamos la barra del título
     	this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.setContentView(R.layout.pdf_send);
        
		pdfFile = null;
        myContext = PrKOperations.this;
		
		pdfItems.clear(); 
		listView = (ListView) findViewById(android.R.id.list);

        // Ocultamos los controles
        fontType = Typeface.createFromAsset(myContext.getAssets(), "fonts/NeutraText-LightAlt.otf");
        TextView myText = (TextView)findViewById(R.id.result1);
        myText.setVisibility(TextView.INVISIBLE);
        myText.setTypeface(fontType);

        myText = (TextView)findViewById(R.id.result2);
        myText.setVisibility(TextView.INVISIBLE);
        myText.setTypeface(fontType);

        myText = (TextView)findViewById(R.id.resultinfo);
        myText.setVisibility(TextView.INVISIBLE);
        myText.setTypeface(fontType);

		findViewById(R.id.logocyl).setVisibility(ImageView.INVISIBLE);
		((ImageView)findViewById(R.id.resultimg)).setImageResource(R.drawable.checked_false);
		findViewById(R.id.resultimg).setVisibility(ImageView.INVISIBLE);
		
		// Conexión con el DNIe
		Intent intent = getIntent();        
		cansDO = new CANSpecDOStore(this);
		canDnie = ((MyAppMcu)getApplicationContext()).getCAN();		
        resolveIntent(intent);
        
        if(tagFromIntent==null)
		{
        	strError = "No hay disponible ningún Dnie NFC";
        	myHandler.post(updateResult);
			return;
		}
				        	
		// Interfaz NfcA o NfcB
    	if( (exNfcA!=null) ||
    		(exNfcB!=null))
    	{
    		if(exIsoDep!=null)
    		{
    			exIsoDep.setTimeout(5000);
    			MyTaskDNIe newTask = new MyTaskDNIe();
    			newTask.execute();
    		}

    	}
		
		///////////////////////////////////////////////////////////////////////////////////
		// Botón de vuelta al Activity anterior
    	findViewById(R.id.Btn_BACK).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// Hemos finalizado así que volvemos al Activity principal
				Intent intent = new Intent(PrKOperations.this, DNIeMcu.class);
				startActivity(intent);
			}
		});
    }
    
    public class MailFile extends javax.mail.Authenticator 
    {    		
		public MailFile(){	}
		
		public void Mail(String user, String pass) { 
			
			// Mantenemos la sesión abierta anteriormente para lectura
			Session session = ((MyAppMcu)getApplicationContext()).getSession();
		        		    
		    try 
		    {
		        Message message = new MimeMessage(session);
		        message.setFrom(new InternetAddress(user));
		        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(m_destino));
		        message.setSubject("Documento firmado");
		        
		        Multipart multipart = new MimeMultipart();
		
		        MimeBodyPart messageBodyPart = new MimeBodyPart();
		        DataSource source;
		        File signedFile = new File(m_PDFoutbox);
	        	source = new FileDataSource(signedFile);
	        	messageBodyPart.setDataHandler(new DataHandler(source));
	        	messageBodyPart.setFileName(m_PDFoutbox);
		        
		        messageBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
		        messageBodyPart.setHeader("Content-ID","<vogue>");
		        
		        multipart.addBodyPart(messageBodyPart);
		        message.setContent(multipart);
		        Transport.send(message);
		    } 
		    catch (MessagingException e) 
		    {
		    	throw new RuntimeException(e);
		    }           
		}   
	}
    
    public void CargarCDF() throws Exception
    { 
    	// Actualizamos el estado
		textoProcessDlg = "Leyendo DNIe...";
		myHandler.post(updateStatus);
		
		// Leemos los certificados
		if(exIsoDep!=null)
		{			
    		try 
    		{   
                // Activamos el modo rápido para agilizar la carga.
                System.setProperty("es.gob.jmulticard.fastmode", "true");
    			    			
    			final DnieProvider p = new DnieProvider();
    			p.setProviderTag(tagFromIntent);
    			p.setProviderCan(canDnie.getCanNumber());
    			Security.insertProviderAt(p, 1);
    			
    			// Cargando KeyStore de tipo MRTD
        		keyStoreDNIe = KeyStore.getInstance("MRTD");
        		keyStoreDNIe.load(null,null);

    	    	// Actualizamos la BBDD de los CAN para a�adir estos datos
    	    	String certSubject = ((FakeX509Certificate)keyStoreDNIe.getCertificate("CertFirmaDigital")).getSubjectDN().toString();
    	    	CANSpecDO newCan = new CANSpecDO(canDnie.getCanNumber(), 
    	    					certSubject.substring((certSubject.indexOf("CN=")+3)), 
    	    					certSubject.substring(certSubject.indexOf("NIF ")+4));
    	    	cansDO.delete(canDnie);
    	    	cansDO.save(newCan);
			}
    		catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new Exception(e.getMessage());
			}
		}
    }
    
    private void FirmarPDF() throws Exception
    {    	
    	// Actualizamos el estado
		textoProcessDlg = "Firmando documento...";
		myHandler.post(updateStatus);
		
    	// Recuperamos las direcciones de los PDFs
		m_PDFinbox	= ((MyAppMcu)getApplicationContext()).getPDF(1);
		m_PDFoutbox = ((MyAppMcu)getApplicationContext()).getPDF(2);
		strError		= null;

		getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
    	
    	// Realizamos la firma del PDF
        PDF_Firmar(keyStoreDNIe);

        // Actualizamos el número de notificaciones
    	((MyAppMcu)getApplicationContext()).setNotifications(MyAppMcu.EVENT_LOAD,((MyAppMcu)getApplicationContext()).getNotifications(MyAppMcu.EVENT_LOAD)-1);
    	((MyAppMcu)getApplicationContext()).setNotifications(MyAppMcu.EVENT_SIGN,((MyAppMcu)getApplicationContext()).getNotifications(MyAppMcu.EVENT_SIGN)+1);

    	// Descargamos el provider del DNIe.
    	//Security.removeProvider("DNIeJCAProvider");
    }
    
    private void EnviarPDF() throws Exception
    {
    	// Actualizamos el estado
		textoProcessDlg = "Enviando documento...";
		myHandler.post(updateStatus);
		
    	//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);
 	    String user = sharedPreferences.getString(SETTING_USER,"");
 	    String pass = sharedPreferences.getString(SETTING_PASS,"");
	 	
		// Enviar el fichero vía SMTP:
	 	MailFile mail = new MailFile();
		mail.Mail(user, pass);
		
		// Movemos el fichero a la carpeta de ENVIADOS
		m_PDFsendbox  = m_PDFoutbox.replace("/Outbox/", "/Enviados/");
		MoveFileSource2Dest(m_PDFoutbox, m_PDFsendbox);
		
		// Actualizamos las notificaciones
		((MyAppMcu)getApplicationContext()).setNotifications(MyAppMcu.EVENT_SIGN,((MyAppMcu)getApplicationContext()).getNotifications(MyAppMcu.EVENT_SIGN)-1);
		
    	// Borramos el fichero original
    	//borrarFichero(m_PDFinbox);
    }
    
    void resolveIntent(Intent intent) {

    	tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        if(tagFromIntent!= null)
        {
        	// Mostramos los interfaces disponibles
        	exNfcA	 = NfcA.get(tagFromIntent);
        	exNfcB	 = NfcB.get(tagFromIntent);
        	exIsoDep = IsoDep.get(tagFromIntent);
        }
        
        // Parse the intent
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
            // When a tag is discovered we send it to the service to be save. We
            // include a PendingIntent for the service to call back onto. This
            // will cause this activity to be restarted with onNewIntent(). At
            // that time we read it from the database and view it.
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            }

            setTitle(R.string.str_nfc_newtag);
        } else {
            finish();
        }
    }

    @Override
    public void onNewIntent(Intent intent) {        
        // Indicamos que ya se ha creado el Intent así que habrá que reiniciarlo, simplemente.
        m_bRestart = true;
        m_success = false;

        // Ocultamos los controles
 		findViewById(R.id.result1).setVisibility(TextView.INVISIBLE);
 		findViewById(R.id.result2).setVisibility(TextView.INVISIBLE);
 		((ImageView)findViewById(R.id.resultimg)).setImageResource(R.drawable.checked_false);
 		findViewById(R.id.resultimg).setVisibility(ImageView.INVISIBLE);
 		findViewById(R.id.resultlist).setVisibility(LinearLayout.INVISIBLE);
 		findViewById(R.id.resultinfo).setVisibility(Button.INVISIBLE);
 		
 		// Borramos los pdfs anteriores
 		pdfFile = null;		
		pdfItems.clear(); 
		
		setIntent(intent);
        resolveIntent(intent);
    }
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode==PDF_VIEWER)
			temporalFile.delete();		
	}
	
	private void MoveFileSource2Dest (String fileSource, String fileDestination) throws Exception
	{
		try
		{
			// Mover el fichero a la carpeta de ENVIADOS
			File source = new File(fileSource);
	    	if(source.exists())
	    	{	
	    		File dest = new File(fileDestination);
	    		InputStream in = new FileInputStream(source);
	            OutputStream out = new FileOutputStream(dest);

	            // Copy the bits from instream to outstream
	            byte[] buf = new byte[1024];
	            int len;
	            while ((len = in.read(buf)) > 0) 
	                out.write(buf, 0, len);
	            
	            // Cerramos los ficheros
	            in.close();
	            out.close();
	            source.delete();
	    	}
		}catch(Exception e)
		{
			throw e;			
		}
	}
}
