package com.cwbuyer.lib;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;

@SuppressLint("DefaultLocale")
public class FileUtil {
	
	public static final String FILE_COMPARE = Environment.getExternalStorageDirectory().getAbsolutePath()
			+ File.separator + "CWBuyer" + File.separator + "init.sys";
	
	private static final String XML_ITEM = "item";
	
	private static final int BUFFER = 2048; 
	
	private static LinkedList<HashMap<String,String>> mAllList = null;
	private static HashMap<String, String> mDataList = null;
	
	// 製成XML檔
	public static String makeXML(String[] attr, String[] value){
		StringBuffer buf = new StringBuffer();
		try{
//			buf.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			buf.append("<xml>");
			buf.append("<item>");
			for(int i = 0; i < attr.length; i++){
				buf.append("<").append(attr[i]).append(">");
				buf.append(value[i]);
				buf.append("</").append(attr[i]).append(">");
			}
			buf.append("</item>");
			buf.append("</xml>");
		}catch(Exception e){
			e.printStackTrace();
		}
		return buf.toString();
	}
	
	// 寫XML到外部檔案
	public static void writeToFile(String filename, String text){
		File file;
		file = new File(filename);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			byte[] data = text.getBytes();
			FileOutputStream fos = new FileOutputStream(file, false);
			fos.write(data);
			fos.close();
		} catch (FileNotFoundException e) {
			Log.e("ERROR", "File FileNotFoundException");
		} catch (IOException e) {
			Log.e("ERROR", "File IOException");
		} catch (SecurityException e) {
			Log.e("ERROR", "File SecurityException");
		}
	}

	// 一起包成 zip
	public static void toZipFile(String[] files, String destZip) {
		try {
			BufferedInputStream origin = null;
			FileOutputStream dest = new FileOutputStream(destZip);
			ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
			byte data[] = new byte[BUFFER];
			for (int i = 0; i < files.length; i++) {
				Log.v("Compress", "Adding: " + files[i]);
				FileInputStream fi = new FileInputStream(files[i]);
				origin = new BufferedInputStream(fi, BUFFER);
				ZipEntry entry = new ZipEntry(files[i]);
				
				out.putNextEntry(entry);
				int count;
				while ((count = origin.read(data, 0, BUFFER)) != -1) {
					out.write(data, 0, count);
				}
				origin.close();
			}
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	// 取得網路資源
	public static InputStream returnStream(String path) {
		InputStream is = null;
		try {
			URL url = new URL (path);
			URLConnection conn = url.openConnection();
			conn.setConnectTimeout(10000); 
			conn.setReadTimeout(10000); 
			conn.connect();
			is = conn.getInputStream();
		} catch (MalformedURLException e) { 
			e.printStackTrace(); 
		} catch (UnsupportedEncodingException e) { 
			e.printStackTrace(); 
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return is;
	}
	
	// 存到外部資料
	public static boolean saveToExternal(InputStream is, String strFullPath){
		File file = new File(strFullPath);
		try{
			if(file.exists() == false){
				if(file.createNewFile() == false){
					return false;
				}
			}
			if(file.exists() == true){
				FileOutputStream fos = new FileOutputStream(file);
				byte[] buf = new byte[1024];   
				int nLength = 0;
				while((nLength = is.read(buf)) > 0){
					fos.write(buf,0,nLength);
				}
				fos.flush();
				fos.close();
				
				return true;
				
			}else{
				return false;
			}
		}catch(IOException e){
			e.printStackTrace();
			return false;
		}
	}
	
	// 複製檔案
	public static void copyFile(String originalFileName, String destFileName)
			throws Exception {
		byte[] buffer = new byte[4096];
		int size = -1;
		FileInputStream fis = new FileInputStream(originalFileName);
		FileOutputStream fos = new FileOutputStream(destFileName);
		while ((size = fis.read(buffer, 0, buffer.length)) != -1) {
			fos.write(buffer, 0, size);
		}
		fis.close();
		fos.close();
		fis = null;
		fos = null;
	}
	
	/**
     *  只取檔名(不含副檔名)
     * @param path
     * @return
     */
    public static String GetFileNameWithoutExtension(String path){
    	String result = null; 
    	try{
          File file = new File (path);
          String fname = file.getName();
          int lastFind = fname.lastIndexOf(".");
          result = fname.substring(0, lastFind);
    	}catch(Exception e){
    		result = "";
    		e.printStackTrace();
    	}
        return result;
    }
    
    /**
     *  只取檔名(含副檔名)
     * @param path
     * @return
     */
    public static String GetFileName(String path){
    	String result = null; 
    	try{
          File file = new File (path);
          result = file.getName();
    	}catch(Exception e){
    		result = "";
    		e.printStackTrace();
    	}
        return result;
    }
    
    // 取得副檔名
    public static String GetFileExtension(String strFile){
    	String extension = null;
    	try{
    		int lastFind = strFile.lastIndexOf(".");
    		if(lastFind > 0){
    			extension = strFile.substring(lastFind, strFile.length());
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return extension;
    }
	
	  /*
	   * 解壓縮Zip
	   */
	  public static void Unzip(String zipFile, String targetDir) {
	    int BUFFER = 4096;
	    String strEntry;

	    try {
	      BufferedOutputStream dest = null;
	      FileInputStream fis = new FileInputStream(zipFile);
	      ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
	      ZipEntry entry;

	      while ((entry = zis.getNextEntry()) != null) {

	        try {
	          Log.i("Unzip: ", "=" + entry);
	          int count;
	          byte data[] = new byte[BUFFER];
	          strEntry = entry.getName();

	          File entryFile = new File(targetDir + strEntry);
	          File entryDir = new File(entryFile.getParent());
	          if (!entryDir.exists()) {
	            entryDir.mkdirs();
	          }

	          FileOutputStream fos = new FileOutputStream(entryFile);
	          dest = new BufferedOutputStream(fos, BUFFER);
	          while ((count = zis.read(data, 0, BUFFER)) != -1) {
	            dest.write(data, 0, count);
	          }
	          dest.flush();
	          dest.close();
	        } catch (Exception ex) {
	          ex.printStackTrace();
	        }
	      }
	      zis.close();
	    } catch (Exception cwj) {
	      cwj.printStackTrace();
	    }
	  }
	  
	  @SuppressWarnings("unused")
	public static boolean uploadFile(String actionUrl, String newName, String zipfile)
	  {
		  boolean bOK = false;
	      String end = "\r\n";
	      String twoHyphens = "--";
	      String boundary = "*****";
	      try
	      {
//	    	  actionUrl = "http://192.168.1.88/ASKSaveFile.aspx?accunt=user";
	        URL url =new URL(actionUrl);
	        HttpURLConnection con=(HttpURLConnection)url.openConnection();
	        con.setDoInput(true);
	        con.setDoOutput(true);
	        con.setUseCaches(false);
	        con.setRequestMethod("POST");
	        /* setRequestProperty */
	        con.setRequestProperty("Connection", "Keep-Alive");
	        con.setRequestProperty("Charset", "UTF-8");
	        con.setRequestProperty("Content-Type",
	                           "multipart/form-data;boundary="+boundary);
	        DataOutputStream ds =
	          new DataOutputStream(con.getOutputStream());
	        ds.writeBytes(twoHyphens + boundary + end);
	        ds.writeBytes("Content-Disposition: form-data; " +
	                      "name=\"file1\";filename=\"" +
	                      newName +"\"" + end);
	        ds.writeBytes(end);
	        
//	        FileInputStream fStream = new FileInputStream(uploadFile);
//	        Bitmap bmp = Utilis.getLimitBitmap(uploadFile, 320, 240);
//	        Bitmap bmp = Utils.getLimitBitmap(pic, 1280, 800); 
//	        if(bmp == null){
//	        	return bOK;
//	        }
//	        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//	        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
	        File file = new File(zipfile);
	        if(file.exists() == true){
		        InputStream isBm = new FileInputStream(new File(zipfile));
	//	        Toast.makeText(this, "上傳中 請稍候...", Toast.LENGTH_SHORT).show();
		        int bufferSize = 1024;
		        long total = 0;
		        byte[] buffer = new byte[bufferSize];
		        int length = -1;
	//	        while((length = fStream.read(buffer)) != -1)
		        while((length = isBm.read(buffer)) != -1)
		        {
		          ds.write(buffer, 0, length);
		          total += length;
		        }
		        ds.writeBytes(end);
		        ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
		        /* close streams */
	//	        fStream.close();
		        isBm.close();
		        
		        ds.flush();
	        InputStream is = con.getInputStream();
	        int ch;
	        StringBuffer b =new StringBuffer();
	        while( ( ch = is.read() ) != -1 )
	        {
	          b.append( (char)ch );
	        }
		        ds.close();
		        bOK = true;
	        }else{
	        	bOK = false;
	        }
	      }
	      catch(UnknownHostException e){
	    	  e.printStackTrace();
	      }
	      catch(Exception e)
	      {
	    	  e.printStackTrace();
	      }
	      return bOK;
	 }
	  
	 // 專門Parse某一段的 Tag
	 public static String getXMLTag(Context cnt, String file, String tag){
		 String value = null;
		 mAllList = new LinkedList<HashMap<String,String>>();
		 mDataList = new HashMap<String,String>();
		 
		 parserXMLFileAll(cnt, file);
		 if(mAllList.size() > 0){
			 HashMap<String, String> data = mAllList.get(0);
			 value = data.get(tag);
		 }
		 
		 mAllList.clear();
		 mDataList.clear();
		 mAllList = null;
		 mDataList = null;
		 
		 if(value == null){
			 return "";
		 }else{
			 return value;
		 }
	 }
	 
	 @SuppressWarnings("resource")
	public static String getFileText(String path){
		 File file = new File(path);
		 StringBuffer text = new StringBuffer();
		 if(file.exists() == true){
			 try {
			     BufferedReader br = new BufferedReader(new FileReader(file));
			     String line;
			     while ((line = br.readLine()) != null) {
			         text.append(line);
			         text.append('\n');
			     }
			 }
			 catch (IOException e) {
				 e.printStackTrace();
			 }
		 }
		 return text.toString();
	 }
	 
	 private static void parserXMLFileAll(Context cnt, String path){
		 File file = new File(path);
		 if(file.exists() == true){
			 try{
				 InputStream is = new FileInputStream(file);
				 requestXml(cnt, is);
			 }catch(Exception e){
				 e.printStackTrace();
			 }
		 }
	 }
	 
	// 下載XML資料
	 public static boolean requestXml(Context context, InputStream input){
			try {
				if (input != null) {
					final XmlPullParser parser = Xml.newPullParser();
					if(input != null){
						parser.setInput(input, "UTF-8");
						parserXml(parser);  // parser Friend XML
						// 回傳 True , 然後讓上層判斷
						if(mAllList != null && mAllList.size() > 0){
							return true;
						}	
					}
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e){
				e.printStackTrace();
			}
			return false;
		}
		
		// 解析 整個 XML 的Function
		@SuppressWarnings("unused")
		private static boolean parserXml(XmlPullParser parser)
				throws XmlPullParserException, IOException {
			
			int type = 0;
			boolean bContinue = true;
			String name;
			int nID = -1;
			final int depth = parser.getDepth();
			
			// 儲存各個XML ITEM 的資料
			if(mDataList != null){
				mDataList.clear();
			}
			// 儲存 每個XML ITEM 的資料
			if(mAllList != null){
				mAllList.clear();
			}
			
			while (bContinue && (type = parser.next()) != XmlPullParser.END_DOCUMENT
					) {
				switch (type) {
				case XmlPullParser.START_TAG:
					name = parser.getName();
					if (name.equalsIgnoreCase(XML_ITEM)) {
						try {
							getXmlItem(parser);
						} catch (XmlPullParserException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					break;
				case XmlPullParser.END_TAG:
				case XmlPullParser.END_DOCUMENT:
					break;
				}
			}
			return true;
		}

		// 解析 latest 的 TAG
		private static void getXmlItem(XmlPullParser parser)
				throws XmlPullParserException, IOException {
			int type = 0;
			boolean bContinue = true;
			String name;
			// 刪除上一次 XML ITEM 的資料
			HashMap<String,String> datalist = new HashMap<String,String>();
			while (bContinue && (type = parser.next()) != XmlPullParser.END_DOCUMENT
					) {
				switch (type) {
				case XmlPullParser.START_TAG:
					name = parser.getName().toLowerCase();
					try{
						datalist.put(name, parser.nextText());
					}catch(Exception e){
						
					}
					break;
				case XmlPullParser.END_TAG:
					name = parser.getName();
					if (name.equalsIgnoreCase(XML_ITEM)) {
						mAllList.add(datalist);
						bContinue = false;
					}
					break;
				case XmlPullParser.END_DOCUMENT:
					break;
				}
			}
		}
		
		
		public static void deltree(File dir) throws FileNotFoundException
	    {
	        if (dir.exists() && dir.isDirectory())
	        {
	            empty(dir);
	            dir.delete();
	        }
	        else
	        {
	            throw new FileNotFoundException("dir not Found!");
	        }
	    }

	    public static void empty(File dir) throws FileNotFoundException
	    {
	        if (dir.exists() && dir.isDirectory())
	        {
	            File[] entries = dir.listFiles();
	            int sz = entries.length;
	            for (int i = 0; i < sz; i++)
	            {
	                if (entries[i].isDirectory())
	                {
	                    deltree(entries[i]);
	                }
	                else
	                {
	                    entries[i].delete();
	                }
	            }
	        }
	        else
	        {
	            throw new FileNotFoundException("dir not Found!");
	        }
	    }
	    
	class NameFilter implements FilenameFilter {
	 String fileExtention;
		public NameFilter (String fileExtention)
		{ this.fileExtention =fileExtention; }
		
		public boolean accept(File dir,String fileName){
			return fileName.endsWith(fileExtention);
		}
	
	}
	    
	    
}
