package com.appli.gui;

import android.Manifest;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.appli.patoche.R;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


 
public class notepad_activity extends Activity 
{
 
    Button newButton,saveButton,openButton;
    EditText text;
    Writer writer;
    CheckBox dontShowAgain;
    String tmp= "";

	private static final int REQUEST_INTERNET = 200;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notepad_layout);
 
        newButton=(Button)findViewById(R.id.newButton);
        saveButton=(Button)findViewById(R.id.saveButton);
        openButton=(Button)findViewById(R.id.openButton);
        text=(EditText)findViewById(R.id.text);

		if (ContextCompat.checkSelfPermission(notepad_activity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
		{
			ActivityCompat.requestPermissions(notepad_activity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_INTERNET);
		}
     
    }
 
    public void buttonAction(View v) 
    {
        final EditText fileName=new EditText(this);
        AlertDialog.Builder ad=new AlertDialog.Builder(this);
        
        ad.setView(fileName);
 
        if (v.getId() == R.id.saveButton)
        {
            ad.setMessage("Save File: [A-Za-z0-9_-].txt ");
 
            ad.setPositiveButton("Save",new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which) 
                {
                	String fichier = fileName.getText().toString();
                	tmp = fichier; // sauvegarde
                	gestion(fichier);

                }
            });
  
 
            ad.setNegativeButton("Cancel",new DialogInterface.OnClickListener() 
            {
	                @Override
	                public void onClick(DialogInterface dialog, int which) 
	                {
	                    dialog.cancel();
	                }
            });
 
            ad.show();
 
        }
 
        if(v.getId()==R.id.openButton)
        {
            ad.setMessage("Open File");
 
            ad.setPositiveButton("Open",new DialogInterface.OnClickListener() 
            {
                	@Override
	                public void onClick(DialogInterface dialog, int which) 
	                {
	                    int c;
	                    text.setText("");
	                    
	                    try
	                    {
	                    		String fichier = "/sdcard/" + fileName.getText().toString();
		            			//File myFile = new File("/sdcard/mysdfile.txt");
	                    		File myFile = new File(fichier);
	                    		
	                    		if(!myFile.exists())
	                    		{
	      	            			Toast.makeText(getBaseContext(), "Le fichier " + fileName.getText().toString() + " n'existe pas !.",Toast.LENGTH_LONG).show();
	                    		}
	                    		else
	                    		{	
	                    			FileInputStream fIn = new FileInputStream(myFile);
	                    			BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
	                    			String aDataRow = "";
	                    			String aBuffer = "";
	                    			while ((aDataRow = myReader.readLine()) != null)
	                    			{
	                    				aBuffer += aDataRow + "\n";
	                    			}
	                    			text.setText(aBuffer);
	                    			myReader.close();
	                    		}
	            		} 
	                    
	                    catch (Exception e) 
	                    {
	            			Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
	            		}
	                    
	                }
            });
 
            ad.setNegativeButton("Cancel",new DialogInterface.OnClickListener()
            {
	                @Override
	                public void onClick(DialogInterface dialog, int which) 
	                {
	                    dialog.cancel();
	                }
            });
 
            ad.show();
        }
 
        if(v.getId()==R.id.newButton) 
        {
            text.setText("");
        }
        
        if(v.getId()==R.id.LoadButton) 
        {
       	 	Intent intent = new Intent(this, files_notepad_activity.class);
			//startActivity(intent);
       	 	startActivityForResult(intent, 0);
        }
        
        
    }
    
    public void gestion(String fichier)
    {
    	
		  String result = check(fichier);
		  
		  if(result.equals("valide"))
		  {
			    String tmp_fichier = "/sdcard/" + fichier;
				File File = new File(tmp_fichier);
			    if(File.exists())
				{
					overwrite();
				}
      	
				else
				{	   
						try
						{
							File.createNewFile();
							FileOutputStream fOut = new FileOutputStream(File);
							OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
							myOutWriter.append(text.getText());
							myOutWriter.close();
							Toast.makeText(getBaseContext(), "File saved", Toast.LENGTH_LONG).show();
						}
						catch (Exception e) 
						{
          				Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
						}
					
				}       
		  }
		  if(result.equals("no_alphanumeric"))
		  {
			  Toast.makeText(getBaseContext(), "Only alhanumeric character [A-Za-z0-9 . _ -] ", Toast.LENGTH_LONG).show();	
		  }
		  if(result.equals("extension"))
		  {
			  Toast.makeText(getBaseContext(), "Extension not allowed: only *.txt ", Toast.LENGTH_LONG).show();	
		  }
		  if(result.equals("empty"))
		  {
			  Toast.makeText(getBaseContext(), "Field is empty ! Try again ", Toast.LENGTH_SHORT).show();
		  }
    	
    	
    	
    }
    
    public void overwrite() 
    {
    	
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View formElementsView = inflater.inflate(R.layout.form_notepad_layout,   null, false);
        
        final CheckBox myCheckBox = (CheckBox) formElementsView.findViewById(R.id.myCheckBox);
        final EditText nameEditText = (EditText) formElementsView.findViewById(R.id.nameEditText);
     
        new AlertDialog.Builder(notepad_activity.this).setView(formElementsView)
        .setTitle("File exists !: ")
                
        .setPositiveButton("Save", new DialogInterface.OnClickListener() 
        {
	        @Override
	        public void onClick(DialogInterface dialog, int id) 
	        {
	        	  if(myCheckBox.isChecked()) 
	        	  {
	        		  try
					  {
	        			  	File myFile = new File("/sdcard/" + tmp);
                  			myFile.createNewFile();
                  			FileOutputStream fOut = new FileOutputStream(myFile);
                  			OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
                  			myOutWriter.append(text.getText());
                  			myOutWriter.close();
                  			Toast.makeText(getBaseContext(), "File overwrite",Toast.LENGTH_SHORT).show();
					  }
					  
	        		  catch (Exception e) 
					  {
          					Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
					  }
	        	  }
	        	  else
	        	  {       // traitement du champ
		        		  String fichier = nameEditText.getText().toString();
		        		  String result = check(fichier);
		        		  
		        		  if(result.equals("valide"))
		        		  {
		        			  try
							  {
			        			  	File myFile = new File("/sdcard/" + fichier);
		                  			myFile.createNewFile();
		                  			FileOutputStream fOut = new FileOutputStream(myFile);
		                  			OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
		                  			myOutWriter.append(text.getText());
		                  			myOutWriter.close();
	                     			Toast.makeText(getBaseContext(), "Saved to other filename",Toast.LENGTH_SHORT).show();	
							  }
			        		  catch (Exception e) 
							  {
		          					Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
							  }
		        			 
		        		  }
		        		  if(result.equals("no_alphanumeric"))
		        		  {
		        			  Toast.makeText(getBaseContext(), "Only alhanumeric character [A-Za-z0-9 . _ -] ", Toast.LENGTH_LONG).show();	
		        		  }
		        		  if(result.equals("extension"))
		        		  {
		        			  Toast.makeText(getBaseContext(), "Extension not allowed: only *.txt ", Toast.LENGTH_LONG).show();	
		        		  }
		        		  if(result.equals("empty"))
		        		  {
		        			  Toast.makeText(getBaseContext(), "Field is empty ! Try again ", Toast.LENGTH_SHORT).show();
		        		  }
	        		  
	        	  }

	        }
        })

        .setNegativeButton("Cancel", new DialogInterface.OnClickListener()
        {
        	public void onClick(DialogInterface dialog, int id) 
        	{
        		dialog.cancel();
        	}
        })  
        
        .show();       
    	 
    	 
    }
    
    public String check(String fichier)
    {
    	String mode = "";
    	int len = fichier.length();
    	if(len != 0)
    	{
     		String extension = fichier.substring(fichier.length() - 4);
     		if(extension.equals(".txt")) // charCount == 1 &&
			{
     				int position = fichier.indexOf(".");
     				String nom_sans_extension = fichier.substring(0, position-1);
     				boolean isValid = nom_sans_extension.matches("[A-Za-z0-9_-]+");
    				if(isValid)
    				{	
    					mode = "valide";		
    				}
    				else
    				{
    					mode = "no_alphanumeric";		
    				}
			}		
    		
    		else
    		{
				mode = "extension";		
    		}
    		
    	}
    	
    	else
    	{
			mode = "empty";		
    	}
    	
    	return(mode);
    	
    }
    
    public ArrayList<String> readFile(String filename)
	{
		 	  	File pipo = new File(filename);	
			 	ArrayList<String> myArr = new ArrayList<String>();
				
				try {
						BufferedReader br = new BufferedReader(new FileReader(pipo));
						String line;
						
						while ((line = br.readLine()) != null)
						{
							myArr.add(line);
						}
						br.close();
				} 
				
				catch (IOException e) 
				{
					e.printStackTrace();
				}
				
				return(myArr);
	}
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		  
		  if(data != null && data.hasExtra("valeur_retour"))
		  {
				  String fichier = data.getExtras().getString("valeur_retour");
				  
				  try
	              {
	              		File myFile = new File("/mnt/sdcard/" + fichier);
	           			FileInputStream fIn = new FileInputStream(myFile);
	           			BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
	           			String aDataRow = "";
	          			String aBuffer = "";
	
	          			while ((aDataRow = myReader.readLine()) != null)
	              		{
	              			aBuffer += aDataRow + "\n";
	              		}
	              		text.setText(aBuffer);
	              		myReader.close();
	      		} 
	              
	            catch (Exception e) 
	            {
	      			Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
	      		}
				  
				ActionBar ab = getActionBar();
				String titre = "Utils01:  " + fichier; 
				ab.setTitle(titre);
		  }
	} 
    
    
}