package com.dniemcu;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class PDFSigned extends Activity {

	List<String> filesPDF = new ArrayList<String>();
	private ArrayList<PDFItem> pdfItems = new ArrayList<PDFItem>();
	
	private CustomArrayAdapter mAdapter;

    private ListView listView;

    private File sentDir;
	private File temporalFile;
		
	private static int PDF_VIEWER = 0x10;

	class pdfFilter implements FilenameFilter {
        public boolean accept(File dir, String name) {
                return (name.endsWith(".pdf"));
        }
    }
	
	@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 !=null) )
			temporalFile.delete();
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Quitamos la barra del título
     	this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.pdf_signed);
        int m_Notifications = 0;
        
		try 
		{
			ImageView texto = (ImageView)findViewById(R.id.txt1);
			texto.setImageResource(R.drawable.texto_det_ver);
			
			pdfItems.clear();
			listView = (ListView) findViewById(android.R.id.list);
			
			// Aseguramos el acceso a los directorios necesarios
            File appDir = getDir("FirmaPDF", MODE_PRIVATE);
 			sentDir = new File(appDir, "Enviados"); 
 			if(!sentDir.exists())
 				sentDir.mkdir();
    	    
		    if (sentDir.listFiles(new pdfFilter()).length > 0)
		    {
	            for (File file : sentDir.listFiles(new pdfFilter())) 
	            {
	            	m_Notifications++;
	            	String fechado = new SimpleDateFormat("dd-MM-yyyy, HH:mm:ss").format(new Date(file.lastModified()));
	            	
	            	Bitmap signedIcon = BitmapFactory.decodeResource(getResources(), R.drawable.pdf_signed2);
	            	pdfItems.add(new PDFItem(signedIcon, file.getName(), "Enviado: "+fechado, (file.length()/1024)+" Kbs"));
	            	filesPDF.add(file.getName());
	            }	            
		    }

			// Dejamos indicado el número de notificaciones
		    ((MyAppMcu)getApplicationContext()).setNotifications(MyAppMcu.EVENT_SEND, m_Notifications);
		    
		    mAdapter = new CustomArrayAdapter(this.getApplicationContext(), android.R.id.list, pdfItems);
		    
		    listView.setAdapter(mAdapter);    
		    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
	        	@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) 
				{
					// Dejamos indicado el fichero sobre el que vamos a trabajar
	        		for(int idx=0;idx<pdfItems.size();idx++)
	        		{
	        			pdfItems.get(idx).selectPDF(false);
	        		}
	        		
	        		// Marcamos el PDF actual
	        		pdfItems.get(arg2).selectPDF(true);
	        		
	        		// Forzamos el repintado
	        		mAdapter.notifyDataSetChanged();
					
	        	    try
	        	    {	
	        	    	// Calculamos la ruta al fichero
		        	    String fileName= sentDir.getPath()+"/"+pdfItems.get(arg2).getFileName();
							        	 
	        	    	// 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 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();
					}
	        	    
				}});
		} 
		catch (Exception e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		///////////////////////////////////////////////////////////////////////////////////
		// Botón de vuelta al Activity anterior
		Button btnPrKBack = (Button)findViewById(R.id.Btn_BACK);
		
		btnPrKBack.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				// Volvemos al Activity anterior
				onBackPressed();
			}
		});
    }
    
    // Clase que define una entrada de documento PDF
 	public class PDFItem {
 		private final String file;
 		private String descr1;
 		private String descr2;
		private final Bitmap imgRes;
		public boolean isSelected;
 		
 		public PDFItem(Bitmap imgRes, String file, String descr1, String descr2) {
 			this.imgRes	= imgRes;
 			this.file 	= file; 
 			this.descr1 = descr1;
 			this.descr2 = descr2;
 			this.isSelected = false;
 		}
 		
 		public void selectPDF(boolean selected)
 		{
 			this.isSelected = selected;
 		}
 		
 		public String getFileName(){
 			return file;
 		}
 		
 		public String getDescription(int type){
 			if(type==1)
 				return descr1;
 			else
 				return descr2;
 		}
 	}
 	
 	private void refreshAdapter() {
 		mAdapter.clear();
		
		for (File file : sentDir.listFiles(new pdfFilter())) 
        {
        	String fechado = new SimpleDateFormat("dd-MM-yyyy, HH:mm:ss").format(new Date(file.lastModified()));
        	Bitmap signedIcon = BitmapFactory.decodeResource(getResources(), R.drawable.pdf_signed2);
        	pdfItems.add(new PDFItem(signedIcon, file.getName(), "Enviado: "+fechado, (file.length()/1024)+" Kbs"));
        	filesPDF.add(file.getName());
        }	
	}
 		
 	public class CustomArrayAdapter extends ArrayAdapter<PDFItem> {
 	    Context context;

 	    public CustomArrayAdapter(Context context, int textViewResourceId, List<PDFItem> objects) {
 	        super(context, textViewResourceId, objects);
 	        this.context = context;
 	    }

 	    /*private view holder class*/
 	    private class ViewHolder {
 	        private TextView txtFileName;
 	        private TextView txtFileDesc1;
 	        private TextView txtFileDesc2;
 	    }
 	    
 	    public View getView(int position, View convertView, ViewGroup parent) {
 	        ViewHolder holder;
 	        PDFItem rowItem = getItem(position);

 	        LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
 	        if (convertView == null) {
 	            convertView = mInflater.inflate(R.layout.rowsignedoperation, parent, false);
 	            holder = new ViewHolder();
 	            holder.txtFileName 	= (TextView) convertView.findViewById(R.id.txtFile);
 	            holder.txtFileDesc1 = (TextView) convertView.findViewById(R.id.txtDescr1);
 	            holder.txtFileDesc2 = (TextView) convertView.findViewById(R.id.txtDescr2);
 	             
 	            convertView.setTag(holder);
 	        } else
 	            holder = (ViewHolder) convertView.getTag();

            // Ajustamos textos y tipo de letra
            Typeface type = Typeface.createFromAsset(context.getAssets(),"fonts/NeutraText-LightAlt.otf");
            holder.txtFileName.setText(rowItem.getFileName());
            holder.txtFileName.setTypeface(type);
            holder.txtFileDesc1.setText(rowItem.getDescription(1));
            holder.txtFileDesc1.setTypeface(type);
            holder.txtFileDesc2.setText(rowItem.getDescription(2));
            holder.txtFileDesc2.setTypeface(type);
            
            if(rowItem.isSelected) {
            	convertView.setBackgroundColor(Color.rgb(192, 199, 78));
            	holder.txtFileName.setTextColor(Color.WHITE);
            	holder.txtFileDesc1.setTextColor(Color.WHITE);
            	holder.txtFileDesc2.setTextColor(Color.WHITE);
            }
            else {
            	//convertView.setBackgroundColor(Color.rgb(243, 244, 208));
            	convertView.setBackgroundColor(Color.TRANSPARENT);
            	holder.txtFileName.setTextColor(Color.BLACK);
            	holder.txtFileDesc1.setTextColor(Color.GRAY);
            	holder.txtFileDesc2.setTextColor(Color.GRAY);
            }
            
            Button btnAbrirPDFView = (Button)  convertView.findViewById(R.id.Btn_abrirpdf);
            btnAbrirPDFView.setOnClickListener(new OnClickListener() {
	    		public void onClick(View v) {
	    			RelativeLayout vwParentRow = (RelativeLayout)v.getParent();				    	
	    			int position = listView.getPositionForView(vwParentRow);
	    			
	    			// Dejamos indicado el fichero sobre el que vamos a trabajar
	        		for(int idx=0;idx<pdfItems.size();idx++)
	        			pdfItems.get(idx).selectPDF(false);
	        		
	        		// Marcamos el PDF actual
	        		pdfItems.get(position).selectPDF(true);
	        		
	        		// Forzamos el repintado
	        		mAdapter.notifyDataSetChanged();

					// Calculamos la ruta al fichero
					String fileName= sentDir.getPath()+"/"+pdfItems.get(position).getFileName();
					
					// Creamos un fichero temporal para poder mostrarlo
					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();
					}
	    		}
    		});
            
            Button deleteImageView = (Button)  convertView.findViewById(R.id.Btn_DESTROYENTRY);
	    	deleteImageView.setOnClickListener(new OnClickListener() {
	    		public void onClick(View v) {
	    			RelativeLayout vwParentRow = (RelativeLayout)v.getParent();				    	
	    			int position = listView.getPositionForView(vwParentRow);
	    			
	    			// Obtenemos la ruta al fichero
					String fileName= sentDir.getPath()+"/"+pdfItems.get(position).getFileName();
					File source = new File(fileName);
					if(source.exists())
						source.delete();
					
					// Actualizamos la lista de documentos disponibles
					refreshAdapter();
	    		}
    		});
 	        
 	        return convertView;
 	    }
 	}
}
