/*******************************************************************************

* Copyright (c) 2007 IONA Technologies PLC

* All rights reserved. This program and the accompanying materials

* are made available under the terms of the Eclipse Public License v1.0

* which accompanies this distribution, and is available at

* http://www.eclipse.org/legal/epl-v10.html

* 

* Contributors:

*     IONA Technologies PLC - initial API and implementation

*******************************************************************************/
package org.eclipse.stp.sc.common.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.eclipse.core.resources.IFile;
import org.eclipse.stp.common.logging.LoggingProxy;

/**
 * @author jma
 *
 */
public class FileUtils {
	
	private static final LoggingProxy LOG = LoggingProxy.getlogger(FileUtils.class);
	
	/**
	 * create ifile from url
	 * this  is called with import wsdl from  url to workspace
	 * @param file
	 * @param urlStr
	 * @return
	 */
    public static void createFromURL(IFile file, String urlStr) {
    	try {
    		LOG.debug("try to create wsdl file from url " + urlStr);
    		URL url = new URL(urlStr);
    		InputStream inputStream = url.openStream();
    		file.create(inputStream, true, null);
    	} catch (Exception e) {
    		LOG.error("error during create wsdlfile from url", e);
    	}
    }
    
    /*
     * create file name from url
     */
    public static String getFileNameFromURL(String urlStr, String extension) {
        if (urlStr.lastIndexOf("/") > 0) {
        	urlStr = urlStr.substring(urlStr.lastIndexOf("/") + 1);
        }
        if (urlStr.lastIndexOf("\\") > 0) {
        	urlStr = urlStr.substring(urlStr.lastIndexOf("\\") + 1);
        }
        if (urlStr.lastIndexOf("?") > 0) {
        	urlStr = urlStr.substring(urlStr.lastIndexOf("?") + 1);
        }
        if (extension != null) {
        	if (urlStr.endsWith(extension)) {
        		return urlStr;
        	} else {
        		return urlStr + extension;
        	}
        }
        return urlStr;
    }
    
    /**
     * read file content
     * @param filePath
     * @return
     */
    public static String getFileContent(String filePath) {
    	StringBuffer sb = new StringBuffer();
    	String line;
    	try {
			BufferedReader reader = new BufferedReader(new FileReader(filePath));
			while ((line = reader.readLine()) != null) {
				sb.append(line);
				sb.append("\n");
			}
			reader.close();
		} catch (Exception e) {
			LOG.error("error read from file", e);
		}
    	return sb.toString();
    }
    
    public static String getURLContent(String urlStr) {
    	StringBuffer sb = new StringBuffer();
		try {
			URL url = new URL(urlStr);
			URLConnection yc = url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(yc
					.getInputStream()));
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				sb.append(inputLine);
				sb.append("\n");
			}
			in.close();
		} catch (Exception e) {
			LOG.error("error read from url", e);
		}
		return sb.toString();
	}
    
    /**
     * return the file name without path
     * 
     * @param path,
     *            file name with path
     * @return, file name only
     */
    public static String getFileName(String path) {
        if (path.lastIndexOf("/") >= 0) {
            return path.substring(path.lastIndexOf("/") + 1, path.length());
        } else if (path.lastIndexOf("\\") >= 0) {
            return path.substring(path.lastIndexOf("\\") + 1, path.length());
        }
        return path;
    }

    public static boolean copyFile(InputStream is, String targetFileName) {
        FileOutputStream fos = null;
        try {
            File targetFile = new File(targetFileName);
            targetFile.createNewFile();
            fos = new FileOutputStream(targetFile);
            int len = 1024;
            byte[] bytes = new byte[len];
            int count = 0;
            while ((count = is.read(bytes)) > 0) {
                fos.write(bytes, 0, count);
            }
            bytes = null;
            return true;
        } catch (Exception e) {
            LOG.error("error during copy file to:" + targetFileName, e);
            return false;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception fose) {

                }
            }
            try {
                is.close();
            } catch (Exception ise) {

            }
        }
    }

    public static String copyFile(String originalFile, String path) {
        FileChannel rbc = null;
        FileChannel wbc = null;
        try {
            File oriFile = new File(originalFile);
            File targetFile = new File(path, oriFile.getName());
            targetFile.createNewFile();

            ByteBuffer bb = ByteBuffer.allocate(0x2000);
            rbc = new FileInputStream(oriFile).getChannel();
            wbc = new FileOutputStream(targetFile).getChannel();
            while (rbc.read(bb) > 0) {
                bb.flip();
                wbc.write(bb);
                bb.clear();
            }
            return path + File.separator + oriFile.getName();
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (rbc != null) {
                try {
                    rbc.close();
                } catch (IOException e) {
                }
            }
            if (wbc != null) {
                try {
                    wbc.close();
                } catch (IOException e) {
                }
            }
        }
        return null;

    }
    
    public static boolean deleteFile(File f) {
        if (f.isDirectory()) {            
            File[] files = f.listFiles();
            
            for (File file : files) {
                boolean deleted = deleteFile(file);

                if (!deleted) {
                    return false;
                }
            }           
        }

        return f.delete();
    }
}
