package com.bizofficer.util.system;

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.InputStream;
import java.io.LineNumberReader;
import java.io.OutputStream;

public class InputOutputToFile {

	//private static final String FILENAME = "E:\\test\\filename.txt";

	public void writeToFile(String data, String filePath) {

		BufferedWriter bw = null;
		FileWriter fw = null;

		try {

			File file = new File(filePath);

			// if file doesnt exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}

			// true = append file
			fw = new FileWriter(file.getAbsoluteFile(), true);
			bw = new BufferedWriter(fw);

			bw.write(data);

			///System.out.println("Done");

		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			try {

				if (bw != null)
					bw.close();

				if (fw != null)
					fw.close();

			} catch (IOException ex) {

				ex.printStackTrace();

			}
		}

	}

	public void overWriteToFile(String data, String filePath) {

		BufferedWriter bw = null;
		FileWriter fw = null;

		try {

			File file = new File(filePath);

			// if file doesnt exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}

			// false = over write file
			fw = new FileWriter(file.getAbsoluteFile(), false);
			bw = new BufferedWriter(fw);

			bw.write(data);

		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			try {

				if (bw != null)
					bw.close();

				if (fw != null)
					fw.close();

			} catch (IOException ex) {

				ex.printStackTrace();

			}
		}

	}
	
	public String readFile(String filePath){
		
		String contentofFile=null;
		
		File file = new File(filePath);
        if (!file.exists()) {
            return "File does not exist";
        }

        BufferedReader reader = null;
        try {
        	StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new FileReader(file));
            String line;
            
            while ((line = reader.readLine()) != null) {
            	sb.append(line);
                sb.append("\n");
                ///line = reader.readLine();
            }
            contentofFile = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

       return contentofFile;
	}
	
	public Boolean findALineInFile(String data, String filePath){
		
		File file = new File(filePath);
        if (!file.exists()) {
            return false;
        }

        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String line;
            while ((line = reader.readLine()) != null) {
            	///System.out.println(">> " + line);
            	if(data.trim().equals(line.trim())){
            		return true;
            	}
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

       return false;
	}
	
	public Integer totalLineCount(String filePath){
		Integer totallinecount = null;
		try {
			File f = new File(filePath);
			if(f.exists()){
				LineNumberReader  lnr = new LineNumberReader(new FileReader(new File(filePath)));
				lnr.skip(Long.MAX_VALUE);
				totallinecount = lnr.getLineNumber() + 1; //Add 1 because line index starts at 0
				// Finally, the LineNumberReader object should be closed to prevent resource leak
				lnr.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return totallinecount;
	}
	
	public void renameFileAfterLimit(Integer limitLines, String filePath){
		try {
			// File (or directory) with old name
			File file = new File(filePath);
			if (file.exists()){

				if(this.totalLineCount(filePath)<limitLines){
					return ;
				}

				MakeDate mkdate = new MakeDate();
				General gen = new General();
				String newFileName = filePath+mkdate.dateToString(mkdate.getCurrentDate("dd-MM-yyyy"),"dd-MM-yyyy")+"-"+gen.getRandomNumber(99, 999);
				file.renameTo(new File(newFileName));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void copyFolder(String source, String destination){
		copyFolder(new File(source), new File(destination));
	}
	
	public static void copyFolder(File source, File destination)
	{
	    if (source.isDirectory())
	    {
	        if (!destination.exists())
	        {
	            destination.mkdirs();
	        }

	        String files[] = source.list();

	        for (String file : files)
	        {
	            File srcFile = new File(source, file);
	            File destFile = new File(destination, file);

	            copyFolder(srcFile, destFile);
	        }
	    }
	    else
	    {
	        InputStream in = null;
	        OutputStream out = null;

	        try
	        {
	            in = new FileInputStream(source);
	            out = new FileOutputStream(destination);

	            byte[] buffer = new byte[1024];

	            int length;
	            while ((length = in.read(buffer)) > 0)
	            {
	                out.write(buffer, 0, length);
	            }
	        }
	        catch (Exception e)
	        {
	            try
	            {
	                in.close();
	            }
	            catch (IOException e1)
	            {
	                e1.printStackTrace();
	            }

	            try
	            {
	                out.close();
	            }
	            catch (IOException e1)
	            {
	                e1.printStackTrace();
	            }
	        }
	    }
	}


	public Long getLastModifiedTime(String filePath){
		try {
			File f = new File(filePath);
			if(f.exists()){
				return f.lastModified();
			}			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String[] getFileNameList(String folderPath){
		try {
			File fileObj = new File(folderPath);
			File[] listOfFiles = fileObj.listFiles();
			String[] filesList = new String[listOfFiles.length];
			for (int i = 0; i < listOfFiles.length; i++) {
			  if (listOfFiles[i].isFile()) {
				  if(listOfFiles[i].getName()!=null && listOfFiles[i].getName().length()>0){
					  filesList[i]=listOfFiles[i].getName();
				  }
			  }
			}
			return filesList;
		}catch (Exception e1)
        {
                e1.printStackTrace();
        }

		return null;	
	}
	
	public String[] getFileNameList(String folderPath, String searchKeyword){
		String[] filesList = null;
		try{
			if(searchKeyword!=null && searchKeyword.length()>0){
				File fileObj = new File(folderPath);
				File[] listOfFiles = fileObj.listFiles();
				
				java.util.List<String> list = new java.util.ArrayList<String>();
				for (int i = 0; i < listOfFiles.length; i++) {
					  if (listOfFiles[i].isFile()) {
						  if(listOfFiles[i].getName()!=null && listOfFiles[i].getName().length()>0 && listOfFiles[i].getName().contains(searchKeyword)){
							  list.add(listOfFiles[i].getName());
						  }
					  }
				}
				
				if(list!=null && list.size()>0){
					filesList = new String[list.size()];
					int i=0;
					for (String fileName: list) {
						filesList[i]=fileName;
						i++;
					}
				}
				
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return filesList;
	}
	
	public Boolean deleteFile(String filePath){
		try{
			File f = new File(filePath);
			if(f!=null && f.exists()){
				return f.delete();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	
	
	
	
}
