package com.imofan.android.basic.update;

import java.io.File;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 自动更新工具类
 * @author user
 *
 */
public class MFUpdateUtils {
   
    /**
     * 获取当前应用的版本信息
     * @param context
     */
    protected static MFAPPInfo getVersionInfo(Context context){
        MFAPPInfo mfappInfo=null;
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            mfappInfo = new MFAPPInfo();
            mfappInfo.setPackageName(packageInfo.packageName);
            mfappInfo.setVersionCode(packageInfo.versionCode);
            mfappInfo.setVersionName(packageInfo.versionName);
        } catch(PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return mfappInfo;
    }
    
    
    /**
     * 检测到的新版本信息
     * @param checkUrl
     * @return
     */
    protected static MFUpdateAPKInfo checkNewVersion(String checkUrl) {
        MFUpdateAPKInfo mfInfo = null;
        try {
            String json = MFHttpUtils.invokeText(checkUrl);
            if(json != null && json.trim().length() > 0) {
                mfInfo = new MFUpdateAPKInfo();
                JSONObject jsonObject = new JSONObject(json);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time = jsonObject.optString("time");
                if(time!=null && !"".equals(time)){
                    mfInfo.setTime(dateFormat.parse(jsonObject.optString("time")));
                }
                mfInfo.setVersionCode(jsonObject.getInt("versionCode"));
                mfInfo.setVersionName(jsonObject.getString("versionName"));
                mfInfo.setDescription(jsonObject.getString("description"));
                mfInfo.setApkPath(jsonObject.getString("url"));
            }
        } catch (Exception e) {
            mfInfo = null;
            e.printStackTrace();
        }
        return mfInfo;
    }
    
    
    
    /**
     * 利用反射获取本地应用中R文件中的资源
     * @param context 上下文
     * @param className R.java中的class Name
     * @param fieldName 要获取的资源name
     * @return
     */
    protected static int getIdByReflection(Context context, String className, String fieldName){
        int id = 0;
        Class<?> idClass;
        Field idField;
        try {
            idClass = Class.forName((new StringBuilder(String.valueOf(context.getPackageName())))
                    .append(".R$").append(className).toString());
            idField = idClass.getField(fieldName);
            id = idField.getInt(fieldName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return id;
    }
    
    
    /**
     * 创建更新提示框中内容
     * @param activity
     * @param updateInfo
     * @return
     */
    protected static View createUpdateDialog(Activity activity,MFUpdateAPKInfo updateInfo){
        LinearLayout linearLayout=new LinearLayout(activity);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.setPadding(12, 5, 12, 0);
        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        
        TextView textView = new TextView(activity);
        textView.setPadding(5, 0, 5, 0);
        textView.setText(replaceBr(updateInfo.getDescription()));
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,18f);
        textView.setTextColor(Color.BLACK);
        linearLayout.addView(textView,param);
        
        return linearLayout;
    }
    
    
    /**
     * 替换字符串中的"<br>"
     * @param str
     * @return 字符串
     */
    public static String replaceBr(String str){
        if(str == null||"".equals(str)){
            return "";
        }
        return str.replaceAll("(?i)<br>", "\n").replace("，", ",");
    }
    
    
    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * @param 存放apk的目录
     * @return 
     */
    protected static boolean deleteDir(File dir) {
        if (null!=dir && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }
    
    //删除文件或目录
    protected static boolean delete(File file) {
        if(!file.exists()){
            return false;
        }else{
            if(file.isFile()){
                return deleteFile(file);
            }else{
                return deleteDirectory(file, true);
            }
        }
    }
    
    //删除目录
    private static boolean deleteDirectory(File dirFile, boolean includeSelf) {
        return deleteDirectory(dirFile, null, includeSelf, false);
    }

    //删除目录
    private static boolean deleteDirectory (
            File dirFile, String extension, boolean includeSelf, boolean onlyFile) {
        if(!dirFile.exists() || !dirFile.isDirectory()){
            return false;
        }
        boolean flag = true;
        File[] files = dirFile.listFiles();
        for(int i=0;i<files.length;i++) {
            if(files[i].isFile()){
                if(extension == null ||
                        files[i].getName().toLowerCase().endsWith("." + extension.toLowerCase())) {
                    flag = deleteFile(files[i]);
                    if(!flag){
                        break;
                    }
                }
            } else {
                if(!onlyFile) {
                    flag = deleteDirectory(files[i], true);
                    if(!flag){
                        break;
                    }
                }
            }
        }

        if(!flag){
            return false;
        }

        if(includeSelf) {
            if(dirFile.delete()){
                return true;
            }else{
                return false;
            }
        } else {
            return true;
        }
    }
    
    //删除文件
    private static boolean deleteFile(File file) {
        if(file.isFile() && file.exists()){
            file.delete();
            return true;
        }else{
            return false;
        }
    }
}
