package cn.yg.util;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
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.LineNumberReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;

/**
 * ¹¤¾ßÀà£¬ËùÓÐÍ¨ÓÃ
 * 
 * @author WBW
 * 
 */
public class Util {
	private static Util util;

	public static Util init() { // µ¥Àý£¬¸öÈËÏ°¹ßÓÃInit,±ê×¼ÊÇgetInstance
		if (util == null)
			util = new Util();
		return util;
	}

	private Util() {

	}
	
	private Context context = null;
	public void setContext(Context c){
		this.context = c;
	}
	public Context getContext(){
		return context;
	}

	/**
	 * 
	 * @param path´«ÈëÂ·¾¶×Ö·û´®
	 * @return File
	 */
	public File creatFileIfNotExist(String path) {
		System.out.println("cr");
		File file = new File(path);
		if (!file.exists()) {
			try {
				new File(path.substring(0, path.lastIndexOf(File.separator)))
						.mkdirs();
				file.createNewFile();

			} catch (IOException e) {
				e.printStackTrace();

			}
		}
		return file;
	}

	/**
	 * 
	 * @param path´«ÈëÂ·¾¶×Ö·û´®
	 * @return File
	 */
	public File creatDirIfNotExist(String path) {
		File file = new File(path);
		if (!file.exists()) {
			try {
				file.mkdirs();

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

			}
		}
		return file;
	}

	/**
	 * 
	 * @param path
	 * @return
	 */
	public boolean IsExist(String path) {
		File file = new File(path);
		if (!file.exists())
			return false;
		else
			return true;
	}

	/**
	 * ´´½¨ÐÂµÄÎÄ¼þ£¬Èç¹ûÓÐ¾ÉÎÄ¼þ£¬ÏÈÉ¾³ýÔÙ´´½¨
	 * 
	 * @param path
	 * @return
	 */
	public File creatNewFile(String path) {
		File file = new File(path);
		if (IsExist(path))
			file.delete();
		creatFileIfNotExist(path);
		return file;
	}

	/**
	 * É¾³ýÎÄ¼þ
	 * 
	 * @param path
	 * @return
	 */
	public boolean deleteFile(String path) {
		File file = new File(path);
		if (IsExist(path))
			file.delete();
		return true;
	}

	// É¾³ýÒ»¸öÄ¿Â¼
	public boolean deleteFileDir(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!IsExist(path)) {
			return flag;
		}
		if (!file.isDirectory()) {

			file.delete();
			return true;
		}
		String[] filelist = file.list();
		File temp = null;
		for (int i = 0; i < filelist.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + filelist[i]);
			} else {
				temp = new File(path + File.separator + filelist[i]);
			}
			if (temp.isFile()) {

				temp.delete();
			}
			if (temp.isDirectory()) {
				deleteFileDir(path + "/" + filelist[i]);// ÏÈÉ¾³ýÎÄ¼þ¼ÐÀïÃæµÄÎÄ¼þ
			}
		}
		file.delete();

		flag = true;
		return flag;
	}

	// É¾³ýÎÄ¼þ¼Ð
	// param folderPath ÎÄ¼þ¼ÐÍêÕû¾ø¶ÔÂ·¾¶

	public void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // É¾³ýÍêÀïÃæËùÓÐÄÚÈÝ
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // É¾³ý¿ÕÎÄ¼þ¼Ð
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// É¾³ýÖ¸¶¨ÎÄ¼þ¼ÐÏÂËùÓÐÎÄ¼þ
	// param path ÎÄ¼þ¼ÐÍêÕû¾ø¶ÔÂ·¾¶
	public boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// ÏÈÉ¾³ýÎÄ¼þ¼ÐÀïÃæµÄÎÄ¼þ
				delFolder(path + "/" + tempList[i]);// ÔÙÉ¾³ý¿ÕÎÄ¼þ¼Ð
				flag = true;
			}
		}
		return flag;
	}

	public String[] getFlieName(String rootpath) {
		File root = new File(rootpath);
		File[] filesOrDirs = root.listFiles();
		if (filesOrDirs != null) {
			String[] dir = new String[filesOrDirs.length];
			int num = 0;
			for (int i = 0; i < filesOrDirs.length; i++) {
				if (filesOrDirs[i].isDirectory()) {
					dir[i] = filesOrDirs[i].getName();

					num++;
				}
			}
			String[] dir_r = new String[num];
			num = 0;
			for (int i = 0; i < dir.length; i++) {
				if (dir[i] != null && !dir[i].equals("")) {
					dir_r[num] = dir[i];
					num++;
				}
			}
			return dir_r;
		} else
			return null;
	}

	/**
	 * //»ñµÃÁ÷
	 * 
	 * @param path
	 * @return
	 * @throws FileNotFoundException
	 * @throws UnsupportedEncodingException
	 */
	public BufferedWriter getWriter(String path) throws FileNotFoundException,
			UnsupportedEncodingException {
		FileOutputStream fileout = null;
		fileout = new FileOutputStream(new File(path));
		OutputStreamWriter writer = null;
		writer = new OutputStreamWriter(fileout, "UTF-8");
		BufferedWriter w = new BufferedWriter(writer); // »º³åÇø
		return w;
	}

	public InputStream getInputStream(String path) throws FileNotFoundException {
		// if(Comments.DEBUG) System.out.println("path:"+path);
		FileInputStream filein = null;
		// if(Comments.DEBUG) System.out.println("2");
		// File file = creatFileIfNotExist(path);
		File file = new File(path);
		filein = new FileInputStream(file);
		BufferedInputStream in = null;
		if (filein != null)
			in = new BufferedInputStream(filein);
		return in;
	}

	public boolean StateXmlControl(String path) {
		File f = new File(path);
		if (!f.exists())
			return false;
		if (f.length() == 0)
			return false;
		return true;
	}

	/**
	 * ½«InputStream×ª»»³ÉbyteÊý×é
	 * 
	 * @param in
	 *            InputStream
	 * @return byte[]
	 * @throws IOException
	 */
	public static byte[] InputStreamTOByte(InputStream in) throws IOException {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] data = new byte[6 * 1024];
		int count = -1;
		while ((count = in.read(data, 0, 4 * 1024)) != -1)
			outStream.write(data, 0, count);
		data = null;
		return outStream.toByteArray();
	}

	/**
	 * ½«OutputStream×ª»»³ÉbyteÊý×é
	 * 
	 * @param in
	 *            OutputStream
	 * @return byte[]
	 * @throws IOException
	 */
	public static byte[] OutputStreamTOByte(OutputStream out)
			throws IOException {

		byte[] data = new byte[6 * 1024];
		out.write(data);
		return data;
	}

	/**
	 * ½«byteÊý×é×ª»»³ÉInputStream
	 * 
	 * @param in
	 * @return
	 * @throws Exception
	 */
	public static InputStream byteTOInputStream(byte[] in) {
		ByteArrayInputStream is = new ByteArrayInputStream(in);
		return is;
	}

	/**
	 * ½«byteÊý×é×ª»»³ÉOutputStream
	 * 
	 * @param in
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	public static OutputStream byteTOOutputStream(byte[] in) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		out.write(in);
		return out;
	}

	/**
	 * °ÑÊäÈëÁ÷ÖÐµÄÊý¾ÝÊäÈëµ½PathÀïµÄÎÄ¼þÀï
	 * 
	 * @param path
	 * @param fileName
	 * @param inputStream
	 * @return
	 */
	public File writeFromInputToSD(String path, InputStream inputStream) {
		File file = null;
		OutputStream output = null;
		try {
			file = creatFileIfNotExist(path);
			output = new FileOutputStream(file);
			byte[] buffer = new byte[4 * 1024];
			int temp;
			while ((temp = inputStream.read(buffer)) != -1) {
				output.write(buffer, 0, temp);
			}
			output.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				output.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return file;
	}

	/**
	 * °ÑÊý¾ÝÊäÈëµ½PathÀïµÄÎÄ¼þÀï
	 * 
	 * @param path
	 * @param fileName
	 * @param inputStream
	 * @return
	 */
	public File writeFromInputToSD(String path, byte[] b) {
		File file = null;
		OutputStream output = null;
		try {
			file = creatFileIfNotExist(path);
			output = new FileOutputStream(file);
			output.write(b);
			output.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				output.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return file;
	}

	/**
	 * ·½·¨£º°ÑÒ»¶ÎÎÄ±¾±£´æµ½¸ø¶¨µÄÂ·¾¶ÖÐ.
	 */
	public void saveTxtFile(String filePath, String text) {
		try {
			// Ê×ÏÈ¹¹½¨Ò»¸öÎÄ¼þÊä³öÁ÷,ÓÃÓÚÏòÎÄ¼þÖÐÐ´ÈëÊý¾Ý.
			creatFileIfNotExist(filePath);
			String txt = readTextLine(filePath);
			text = text + txt;
			FileOutputStream out = new FileOutputStream(filePath);
			// ¹¹½¨Ò»¸öÐ´ÈëÆ÷,ÓÃÓÚÏòÁ÷ÖÐÐ´Èë×Ö·ûÊý¾Ý
			OutputStreamWriter writer = new OutputStreamWriter(out, "gb2312");
			writer.write(text);
			// ¹Ø±ÕWriter,¹Ø±ÕÊä³öÁ÷
			writer.close();
			out.close();
		} catch (Exception e) {
			String ext = e.getLocalizedMessage();
			// Toast.makeText(this, ext, Toast.LENGTH_LONG).show();
		}

	}

	public void clearTxtFile(String filePath) {
		try {
			// Ê×ÏÈ¹¹½¨Ò»¸öÎÄ¼þÊä³öÁ÷,ÓÃÓÚÏòÎÄ¼þÖÐÐ´ÈëÊý¾Ý.
			String text = "";
			FileOutputStream out = new FileOutputStream(filePath);
			// ¹¹½¨Ò»¸öÐ´ÈëÆ÷,ÓÃÓÚÏòÁ÷ÖÐÐ´Èë×Ö·ûÊý¾Ý
			OutputStreamWriter writer = new OutputStreamWriter(out, "gb2312");
			writer.write(text);
			// ¹Ø±ÕWriter,¹Ø±ÕÊä³öÁ÷
			writer.close();
			out.close();
		} catch (Exception e) {
			String ext = e.getLocalizedMessage();
			// Toast.makeText(this, ext, Toast.LENGTH_LONG).show();
		}
	}

	// ¶ÁÈ¡Ò»¸ö¸ø¶¨µÄÎÄ±¾ÎÄ¼þÄÚÈÝ,²¢°ÑÄÚÈÝÒÔÒ»¸ö×Ö·û´®µÄÐÎÊ½·µ»Ø
	public String readTextLine(String textFile) {
		try {
			// Ê×ÏÈ¹¹½¨Ò»¸öÎÄ¼þÊäÈëÁ÷,¸ÃÁ÷ÓÃÓÚ´ÓÎÄ±¾ÎÄ¼þÖÐ¶ÁÈ¡Êý¾Ý
			FileInputStream input = new FileInputStream(textFile);
			// ÎªÁËÄÜ¹»´ÓÁ÷ÖÐ¶ÁÈ¡ÎÄ±¾Êý¾Ý,ÎÒÃÇÊ×ÏÈÒª¹¹½¨Ò»¸öÌØ¶¨µÄReaderµÄÊµÀý,
			// ÒòÎªÎÒÃÇÊÇ´ÓÒ»¸öÊäÈëÁ÷ÖÐ¶ÁÈ¡Êý¾Ý,ËùÒÔÕâÀïÊÊºÏÊ¹ÓÃInputStreamReader.
			InputStreamReader streamReader = new InputStreamReader(input,
					"gb2312");
			// ÎªÁËÄÜ¹»ÊµÏÖÒ»´Î¶ÁÈ¡Ò»ÐÐÎÄ±¾µÄ¹¦ÄÜ,ÎÒÃÇÊ¹ÓÃÁË LineNumberReaderÀà,
			// Òª¹¹½¨LineNumberReaderµÄÊµÀý,±ØÐëÒª´«Ò»¸öReaderÊµÀý×ö²ÎÊý,
			// ÎÒÃÇ´«ÈëÇ°ÃæÒÑ¾­¹¹½¨ºÃµÄReder.
			LineNumberReader reader = new LineNumberReader(streamReader);
			// ×Ö·û´®lineÓÃÀ´±£´æÃ¿´Î¶ÁÈ¡µ½µÄÒ»ÐÐÎÄ±¾.
			String line = null;
			// ÕâÀïÎÒÃÇÊ¹ÓÃÒ»¸öStringBuilderÀ´´æ´¢¶ÁÈ¡µ½µÄÃ¿Ò»ÐÐÎÄ±¾,
			// Ö®ËùÒÔ²»ÓÃString,ÊÇÒòÎªËüÃ¿´ÎÐÞ¸Ä¶¼»á²úÉúÒ»¸öÐÂµÄÊµÀý,
			// ËùÒÔÀË·Ñ¿Õ¼ä,Ð§ÂÊµÍ.
			StringBuilder allLine = new StringBuilder();
			// Ã¿´Î¶ÁÈ¡µ½Ò»ÐÐ,Ö±µ½¶ÁÈ¡Íê³É
			while ((line = reader.readLine()) != null) {
				allLine.append(line);
				// ÕâÀïÃ¿Ò»ÐÐºóÃæ,¼ÓÉÏÒ»¸ö»»ÐÐ·û,LINUXÖÐ»»ÐÐÊÇ¡±\n¡±,
				// windowsÖÐ»»ÐÐÊÇ¡±\r\n¡±.
				allLine.append("\n");
			}
			// °ÑReaderºÍStream¹Ø±Õ
			streamReader.close();
			reader.close();
			input.close();
			// °Ñ¶ÁÈ¡µÄ×Ö·û´®·µ»Ø
			return allLine.toString();
		} catch (Exception e) {
			// Toast.makeText(this, e.getLocalizedMessage(),
			// Toast.LENGTH_LONG).show();
			return "";
		}
	}

	// ×ª»»dipÎªpx
	public int convertDipOrPx(Context context, int dip) {
		float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));
	}

	// ×ª»»pxÎªdip
	public int convertPxOrDip(Context context, int px) {
		float scale = context.getResources().getDisplayMetrics().density;
		return (int) (px / scale + 0.5f * (px >= 0 ? 1 : -1));
	}

	/**
	 * ½«pxÖµ×ª»»ÎªspÖµ£¬±£Ö¤ÎÄ×Ö´óÐ¡²»±ä
	 * 
	 * @param pxValue
	 * @param fontScale
	 *            £¨DisplayMetricsÀàÖÐÊôÐÔscaledDensity£©
	 * @return
	 */
	public int px2sp(Context context, float pxValue) {
		float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
		return (int) (pxValue / fontScale + 0.5f);
	}

	/**
	 * ½«spÖµ×ª»»ÎªpxÖµ£¬±£Ö¤ÎÄ×Ö´óÐ¡²»±ä
	 * 
	 * @param spValue
	 * @param fontScale
	 *            £¨DisplayMetricsÀàÖÐÊôÐÔscaledDensity£©
	 * @return
	 */
	public int sp2px(Context context, float spValue) {
		float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
		return (int) (spValue * fontScale + 0.5f);
	}

	// °Ñ×Ö¼Ó³¤£¬Ê¹Æä¿ÉÒÔ¹ö¶¯£¬ÔÚÒôÀÖ½çÃæ
	public String dealString(String st, int size) {
		int value = size;
		if (st.length() >= value)
			return "  " + st + "  ";
		else {
			int t = (value - st.length()) / 2;
			for (int i = 0; i < t; i++) {
				st = " " + st + "  ";
			}
			return st;
		}
	}

	public String getTimeByFormat(String format) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		Date curDate = new Date(System.currentTimeMillis());// »ñÈ¡µ±Ç°Ê±¼ä
		String str = formatter.format(curDate);
		return str;
	}

	public String getDateTimeBylong(long time_data, String dateformat_batt) {
		java.util.Date date = new java.util.Date(time_data);
		SimpleDateFormat format = new SimpleDateFormat(dateformat_batt);
		return format.format(date);
	}

	// È¡Ç°ÃæµÄÃû×Ö¡¡"."
	public String getNameByFlag(String source, String flag) {
		// String[] source_spli = source.split(flag);
		String s = source.toLowerCase().replace(flag, "");
		return s.trim();
	}

	/**
	 * È¡AssetÎÄ¼þ¼ÐÏÂÎÄ¼þ
	 * @param paramContext
	 * @param paramString
	 * @return
	 * @throws IOException
	 */
	public InputStream getAssetsInputStream(Context paramContext,
			String paramString) throws IOException {
		return paramContext.getResources().getAssets().open(paramString);
	}
	
	//ÒÔÊ¡ÄÚ´æµÄ·½Ê½¶ÁÈ¡Í¼Æ¬
		public Bitmap getBitmap(InputStream is){
			   BitmapFactory.Options opt = new BitmapFactory.Options();   
		        opt.inPreferredConfig = Bitmap.Config.RGB_565;    
		       opt.inPurgeable = true;   
		       opt.inInputShareable = true; 
		       opt.inSampleSize = 4;
		          //»ñÈ¡×ÊÔ´Í¼Æ¬   
		       //InputStream is = mContext.getResources().openRawResource(resId);   
		           return BitmapFactory.decodeStream(is,null,opt);   
		}
		
		
		//º¯ÊýÄÜÊ¹Í¼Æ¬³äÂúÕû¸öÆÁÄ»
		public  Bitmap FitTheScreenSizeImage(Bitmap m,int ScreenWidth, int ScreenHeight)
		{
		        float width  = (float)ScreenWidth/m.getWidth();
		        float height = (float)ScreenHeight/m.getHeight();
		        Matrix matrix = new Matrix();
		        matrix.postScale(width,height);
		        return Bitmap.createBitmap(m, 0, 0, m.getWidth(), m.getHeight(), matrix, true);
		 }
		
		
		 /***
         * Í¼Æ¬µÄËõ·Å·½·¨
         * 
         * @param bgimage
         *            £ºÔ´Í¼Æ¬×ÊÔ´
         * @param newWidth
         *            £ºËõ·Åºó¿í¶È
         * @param newHeight
         *            £ºËõ·Åºó¸ß¶È
         * @return
         */
        public  Bitmap zoomImage(Bitmap bgimage, double newWidth,
                        double newHeight) {
                // »ñÈ¡Õâ¸öÍ¼Æ¬µÄ¿íºÍ¸ß
                float width = bgimage.getWidth();
                float height = bgimage.getHeight();
                // ´´½¨²Ù×÷Í¼Æ¬ÓÃµÄmatrix¶ÔÏó
                Matrix matrix = new Matrix();
                // ¼ÆËã¿í¸ßËõ·ÅÂÊ
                float scaleWidth = ((float) newWidth) / width;
                float scaleHeight = ((float) newHeight) / height;
                // Ëõ·ÅÍ¼Æ¬¶¯×÷
                matrix.postScale(scaleWidth, scaleHeight);
                Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                                (int) height, matrix, true);
                return bitmap;
        }
        
        //drawable×ª»¯Îªbitmap
        public static Bitmap drawableToBitmap(Drawable drawable) {  
        	   int width = drawable.getIntrinsicWidth();  
        	   int height = drawable.getIntrinsicHeight();  
        	   Bitmap bitmap = Bitmap.createBitmap(width, height, drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);  
        	   Canvas canvas = new Canvas(bitmap);  
        	   drawable.setBounds(0, 0, width, height);  
        	   drawable.draw(canvas);  
        	   return bitmap;  
        	  
        	}  

}
