package com.tcl.customerapi;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

public class FileUtil {

	/**
     * 删除文件，可以是文件或文件夹
     *
     * @param fileName
     *            要删除的文件名
     * @return 删除成功返回true，否则返回false
     */
    public static boolean delete(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            Log.i("DeleteFileUtil","删除文件失败:" + fileName + "不存在！");
            return false;
        } else {
            if (file.isFile())
                return deleteFile(fileName);
            else
                return deleteDirectory(fileName);
        }
    }
 
    /**
     * 删除单个文件
     *
     * @param fileName
     *            要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
        	
    	    boolean result = false;  
    	    int tryCount = 0;  

    	    while(!result && tryCount++ <10)  {
        	    try {
        	    	System.gc();
        	    	result = file.delete();
                	Log.i("DeleteFileUtil","删除单个文件" + fileName + "结果"+result+"，删除次数，"+tryCount);
        	    }catch(Exception e) {
        	    	e.printStackTrace();
        	    	Log.i("DeleteFileUtil","删除单个文件报错，Exception");
        	    }
    	    	
    	    } 
        	
            if (result) {
            	Log.i("DeleteFileUtil","删除单个文件" + fileName + "成功！");
                return true;
            } else {
            	Log.i("DeleteFileUtil","删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
        	Log.i("DeleteFileUtil","删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }
 
    /**
     * 删除目录及目录下的文件
     *
     * @param dir
     *            要删除的目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String dir) {
        // 如果dir不以文件分隔符结尾，自动添加文件分隔符
        if (!dir.endsWith(File.separator))
            dir = dir + File.separator;
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            System.out.println("删除目录失败：" + dir + "不存在！");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = FileUtil.deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
            // 删除子目录
            else if (files[i].isDirectory()) {
                flag = FileUtil.deleteDirectory(files[i]
                        .getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag) {
        	Log.i("DeleteFileUtil","删除目录失败！");
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {
        	Log.i("DeleteFileUtil","删除目录" + dir + "成功！");
            return true;
        } else {
            return false;
        }
    }

    
  //判断文件是否存在
    public static boolean fileIsExists(String strFile)  
    {  
        try  
        {  
            File f=new File(strFile);  
            if(!f.exists())  
            {  
                    return false;  
            }  
  
        }  
        catch (Exception e)  
        {  
            return false;  
        }  
  
        return true;  
    } 
    
    //判断文件是否存在
    public static boolean isFile(String strFile)  
    {  
        try  
        {  
            File f=new File(strFile);  
            if(f.exists() && f.isFile())  
            {  
                    return true;  
            }else{
            	return false;
            }
  
        }  
        catch (Exception e)  
        {  
            return false;  
        }  
  
    } 
    
    public static List<String> readLineFile(String filename) {
    	Log.i("api","filename "+filename);
    	File file = new File(filename);
    	FileInputStream in = null;
    	InputStreamReader inReader = null;
        List<String> mUrlLists = null;
        try {
            mUrlLists = new ArrayList<String>();
            in = new FileInputStream(file);
            inReader = new InputStreamReader(in, "GB2312");
//            InputStreamReader inReader = new InputStreamReader(in, "UTF-8");
            BufferedReader bufReader = new BufferedReader(inReader);
            String line = null;
            int i = 0;
            while ((line = bufReader.readLine()) != null) {
                mUrlLists.add(line);
                i++;
            }
            bufReader.close();
            inReader.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
        	try {
            	if(inReader!=null) {
            		inReader.close();
            	}
            	if(in!=null) {
            		in.close();
            	}
        	}catch(IOException e) {
        		e.printStackTrace();
        		Log.i("api","IOException");
        	}

        }
        return mUrlLists;
    }
    
    

    /**
     * 将数据存到文件中
     * @param data 需要保存的数据
     * @param filepath 文件路径
     */
    public static void saveDataToFile(String data, String filepath)
    {
        FileOutputStream out;
        BufferedWriter writer = null;
        File file = new File(filepath);
        try {
            out = new FileOutputStream(file);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(data);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("FileUtil", "写入文件失败");
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                Log.e("FileUtil", e.getMessage());
            }
        }
    }

    /**
     * 从文件中读取数据
     * @param filepath 文件路径
     * @return 从文件中读取的数据
     */
    public static String loadDataFromFile(String filepath) {
        String line = "";
        try {
            File filename = new File(filepath);
            InputStreamReader reader = new InputStreamReader(new FileInputStream(filename));
            BufferedReader br = new BufferedReader(reader);
            line = br.readLine();
            br.close();
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
       return  line;
    }
    
    public static List<String> readSettingConfig(String filepath) {
        StringBuilder buffer = new StringBuilder();
        String lineText = null;
        try {
            File file = new File(filepath);
            if (file.isFile() && file.exists()) {
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), "utf-8");
                BufferedReader bufferedReader = new BufferedReader(read);
                while ((lineText = bufferedReader.readLine()) != null) {
                    buffer.append(lineText);
                }
                read.close();
            } else {
                return null;
            }
            JSONObject jsonObject = new JSONObject(buffer.toString());
            JSONArray modeObljecList = new JSONArray();
            List<String> modeList = new ArrayList<String>();
            if (jsonObject.has("Model")) {
                modeObljecList = jsonObject.getJSONArray("Model");
            }
            int size = modeObljecList.length();
            for (int i = 0; i < size; i++) {
                JSONObject mode = new JSONObject(modeObljecList.get(i).toString());
                Iterator<String> keyIter = mode.keys();
                String key;
                while ((keyIter.hasNext())) {
                    key = keyIter.next();
                    modeList.add(key);
                }
            }
            return modeList;
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("FunctionSettingMenu", "readSettingConfig:  fail " + e.getMessage());
            return null;
        }
    }
}
