package de.memtext.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
* Functionality to add suffixes to filenames and to copy files
*
 */
public class FileUtils {

	// don't instantiate
	private FileUtils() {
	}
	
	/**
	 * returns how old in minutes
	 * @param f
	 * @return
	 */
	public static int getHowOld(File f)
	{
	    long now=new java.util.Date().getTime();
	    return (int) ((now-f.lastModified())/(1000*60));
	}
	
	/**
	 * Removes the suffix of a filename 
	 * For example getFileNameWithoutSuffix("test.txt") would return
	 * test
	 * @param String filename
	 * @return
	 */
	public static String getFileNameWithoutSuffix(String filename) {
		int index = filename.indexOf(".");
		if (index == -1)
			throw new IllegalArgumentException(filename + " doesn't contain .");
		filename =filename.substring(0, index);
				

		return filename;
	}
    /**
     * Addes a suffix to a filename before the usual .
     * For example addToEndOfFileName("test.txt","1") would return
     * test1.txt
     * @param String filename
     * @param suffix
     * @return
     */
    public static String addToEndOfFileName(String filename, String suffix) {
        int index = filename.indexOf(".");
        if (index == -1)
            throw new IllegalArgumentException(filename + " doesn't contain .");
        filename =
            filename.substring(0, index)
                + suffix
                + filename.substring(index, filename.length());

        return filename;
    }

	
	
	/**
	 * 
	 * @param dir - directory to search in
	 * @param beginning - required beginning of file name, may be null
	 * @param endings - a single ending like .htm or more .htm|.html
	 * @return File[] - array only files, no directories are returned
	 */
	static public File[] getFileList(File dir,String beginning,String endings)
	{
	    FilenamesFilter filt=new FilenamesFilter(null,endings,beginning);
	    filt.setAllDirsAccepted(false);
	    return dir.listFiles(filt);
	}
	/**
	 * Creates a copy of a file
	 * @param String source
	 * @param String target
	 * @throws Exception
	 */
	static public void copyFile(String source, String target)
		throws IOException {
		copyFile(new File(source), new File(target));
	}
	/**
		 * Creates a copy of a file
		 * @param File source
		 * @param File target
		 * @throws Exception
		 */
	static public void copyFile(File source, File target) throws IOException {
		FileInputStream is = null;
		FileOutputStream os = null;

		BufferedInputStream in = null;
		BufferedOutputStream out = null;

		try {
			is = new FileInputStream(source);
			os = new FileOutputStream(target);

			in = new BufferedInputStream(is);
			out = new BufferedOutputStream(os);

			int buffer_size = 32768;
			byte[] buffer = new byte[buffer_size];

			int len = in.read(buffer, 0, buffer_size);
			while (len != -1) {
				out.write(buffer, 0, len);
				len = in.read(buffer, 0, buffer_size);
			}
			in.close();
			is.close();
			out.close();
			os.close();
		} catch (FileNotFoundException fe) {
			throw new FileNotFoundException(
				"Die Datei " + source + " konnte nicht gefunden werden!");
		} catch (IOException e) {
			throw new IOException("Couldn't copy file " + e.toString());
		}
	}
	public static void createZipFile(String pathToZipUp, String pathToSaveTo) {
		
			createZipFile(pathToZipUp, "", pathToSaveTo);
		}
		
		public static void createZipFile(
			String pathToZipUp,
			String relPath,
			String pathToSaveTo) {
			try {
				FileOutputStream fos = new FileOutputStream(pathToSaveTo);
				ZipOutputStream zos = new ZipOutputStream(fos);

				zos.setMethod(ZipOutputStream.DEFLATED);
				
				if (!relPath.equals("")&&pathToZipUp.lastIndexOf("\\") + 1 != pathToZipUp.length())
				pathToZipUp += "\\";
				System.out.println(pathToZipUp + relPath);
				File f = new File(pathToZipUp + relPath);
				String[] files = f.list();
				if (pathToZipUp.lastIndexOf("\\") + 1 != pathToZipUp.length())
									pathToZipUp += "\\";
				for (int y = 0; y < files.length; y++) {
					//build fully qualified path for each file in directory
					//check for / at the end of the path 
					String fullpath = pathToZipUp;
					if (!relPath.equals(""))
						fullpath += relPath + "\\";
					fullpath += files[y];
					File aFile = new File(fullpath);

					if (aFile.isDirectory()) {
						//recursive call to include all files in the subdirectories
						// Vector subDir = new Vector();
						// subDir.addElement(fullpath);
						if (relPath.equals(""))
							relPath = files[y];
						else
							relPath += "\\" + files[y];
						createZipFile(fullpath, relPath, pathToSaveTo);
					} else {
						byte[] temp = new byte[files[y].length()];

						try {
							FileInputStream fis = new FileInputStream(aFile);

							CRC32 crc32 = new CRC32();
							int n;

							while ((n = fis.read(temp)) > -1) {
								crc32.update(temp, 0, n);
							}

							fis.close();
							String shortName =
								files[y].substring(fullpath.length());
							ZipEntry ze = new ZipEntry(shortName);
							ze.setSize(aFile.length());
							ze.setTime(aFile.lastModified());
							ze.setCrc(crc32.getValue());
							zos.putNextEntry(ze);
							fis = new FileInputStream(aFile);

							while ((n = fis.read(temp)) > -1) {
								zos.write(temp, 0, n);
							}

							fis.close();
							zos.closeEntry();
						} catch (FileNotFoundException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
				} //end for loop
				zos.close();

			} catch (FileNotFoundException e) {
				e.printStackTrace();     
			} catch (Exception e) {
				e.printStackTrace();
			}

			return;
		}
		public static void main(String a[]) {
			List<File> l=getFileList("/home/superx/git/superx/superx/WEB-INF/conf/edustore/db/conf","mo*.xsl,g*.xsl");
			for (Iterator<File> it=l.iterator();it.hasNext();)
			{
				System.out.println(it.next());
			}
		}
        public static void download(URL url,File targetFile) throws IOException {
        URLConnection conn = url.openConnection();
        InputStream inStream = conn.getInputStream();
        FileOutputStream os = new FileOutputStream(targetFile);
        
        BufferedInputStream bufferedInStream = new BufferedInputStream(inStream);
        BufferedOutputStream bufferedOutStream = new BufferedOutputStream(os);
        
        int buffer_size = 32768;
        byte[] buffer = new byte[buffer_size];
        
        int len = inStream.read(buffer, 0, buffer_size);
        while (len != -1) {
            bufferedOutStream.write(buffer, 0, len);
            len = bufferedInStream.read(buffer, 0, buffer_size);
        }
        bufferedInStream.close();
        inStream.close();
        bufferedOutStream.close();
        os.close();
          }
        public static String removeProblemChars(String name) {
           String result=name.replace('\\','-');
           result=result.replace('/','-');
           result=StringUtils.replace(result, " - ", "-");
           result=StringUtils.replace(result, " -", "-");
           result=StringUtils.replace(result, "- ", "-");
           result=result.replace(' ','_');
           result=result.replace('*','_');
           result=result.replace('?','_');
           result=result.replace(',','_');
           return result;
        }
        
        public static List<File> getFileList(String dir,String regex)
        {
        	List<File> resultFiles=new LinkedList<File>();
          	File fDir = new File(dir);
    	    File[] files = fDir.listFiles();
    	    
    	    StringTokenizer st=new StringTokenizer(regex,",");
    	    while (st.hasMoreTokens())
    	    {
    	    	String pattern=st.nextToken();
    	    	pattern=pattern.replace(".", "\\.");  //escape the dot first
    	    	pattern=pattern.replace("?", ".?").replace("*", ".*");
    	   
        	    for (File file : files) {
        	    	if (file.getName().matches(pattern)) resultFiles.add(file);
        	        }
    	    }
        return resultFiles;
	}
        public static String getFileContentsWithEncoding(String filePath, String encoding) throws FileNotFoundException,IOException {
            File f = new File(filePath);
 
            String fileContents = "";
            if (encoding == null || encoding.trim().equals("")) {
                encoding = System.getProperty("file.encoding");
            }
                // --- IputStream und OutputStream generieren ---//
                FileInputStream fis = new FileInputStream(f);
                // Wenn Quelldatei Unicode, dann speziellen Reader nutzen
                BufferedReader in;
                //BufferedReader ist schneller bei großen Dateien
                in = new BufferedReader(new InputStreamReader(fis, encoding));
                // --- Output-Stream der temporären Datei erzeugen ---//
                StringWriter out = new StringWriter();
                // --- Verarbeiten der Datei ---//
                String text;
                text = in.readLine();
                while (text != null) { // Datei nicht leer
                    out.write(text);
                    out.write(System.getProperty("line.separator"));
                    text = in.readLine();
                }
                if (!(out == null)) {
                    fileContents = out.toString();
                }
           
            return fileContents;
        }

}