/**
 * 文件名：LogRecorder.java
 * 描述：Log记录封装类(生成Log日志并写入文件)
 * 包名：cn.com.kmlt.monstarBase.utils.logger
 * 作者：WENJQ
 * 创建日期：2016年05月26日
 * 
 */
package com.mgq.base.utils.logger;

import android.content.Context;
import android.os.Environment;

import com.tofly.ghrq_route.base.C;
import com.tofly.ghrq_route.module.deviceInfo.DeviceInfoTool;
import com.tofly.ghrq_route.module.gps.GpsTool;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.util.date.DateUtils;
import com.tofly.ghrq_route.common.util.sharedPreference.SharePreUtil;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;


public class LogRecorder {

	public static String getLogPath(Context context, String userid, final String dir, final String fileName, String ymd){
        String rootPath = dir;
        if (userid != null && !userid.isEmpty()){
            rootPath = dir + userid + "/";
        }
        File root = new File(rootPath);

		File dest = new File(root.getAbsolutePath() + "//" + fileName
				+ "_" + ymd + ".txt");

		return dest.getPath();
	}

	public static String getLogPath(Context context, String userid, final String dir, final String fileName){
		String today = DateUtils.getYMD();
		return getLogPath(context, userid, dir, fileName, today);
	}

	public static void writeLog2Sdcard(final Context context,
			final String content, final String fileName) {

		Thread thread = new Thread(new Runnable() {

			public void run() {
				// TODO Auto-generated method stub
				File dir = new File(Environment.getExternalStorageDirectory()
						.getAbsolutePath()
						+ "//"
						+ context.getApplicationContext().getPackageName());

				dir.mkdirs();

				File dest = new File(dir.getAbsolutePath() + "//" + fileName
						+ "_" + new Date().getTime() + ".txt");
				try {
					BufferedWriter writer = new BufferedWriter(new FileWriter(
							dest));
					writer.write(content);
					writer.flush();
					writer.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});

		thread.start();

	}

	public static void writeLog2Sdcard(final Context context, final String userid,
									   final String content, final String dir, final String fileName) {

		if (!C.bLogDeviceGpsInfo_debug)
			return;

		Thread thread = new Thread(new Runnable() {

			public void run() {
				// TODO Auto-generated method stub
				String rootPath = dir;
                if (userid != null && !userid.isEmpty()){
                    rootPath = dir + userid + "/";
                }
				File root = new File(rootPath);

				root.mkdirs();

				File dest = new File(root.getAbsolutePath() + "//" + fileName
						+ "_" + DateUtils.getYMD() + ".txt");
				try {
					BufferedWriter writer = new BufferedWriter(new FileWriter(
							dest, true));
                    writer.write(new Date().toString());
                    writer.newLine();
					writer.write(content);
                    writer.newLine();
					writer.flush();
					writer.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});

		thread.start();
	}

	public static void writeLog2SdcardDebug(final Context context, final String user_id,
									   final String content, final String dir, final String fileName) {

		if (!C.bLogDeviceGpsInfo_debug)
			return;

		Thread thread = new Thread(new Runnable() {

			public void run() {
				// TODO Auto-generated method stub
				String rootPath = dir;
				String userid = user_id;
				if (userid != null && !userid.isEmpty()){
					rootPath = dir + userid + "/";
				}else {
					UserBean rememberedUser = SharePreUtil.getLoginInfo(context);
					if (rememberedUser != null)
						userid = rememberedUser.getUserid();
				}
				File root = new File(rootPath);

				root.mkdirs();

				File dest = new File(root.getAbsolutePath() + "//" + fileName
						+ "_" + DateUtils.getYMD() + ".txt");
				try {
					BufferedWriter writer = new BufferedWriter(new FileWriter(
							dest, true));
					writer.write(content);
					writer.flush();
					writer.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});

		thread.start();
	}

	public static String getDeviceLogPath(Context context, String userid){
		String dir = C.dir.log;
		String fileName = DeviceInfoTool.class.getSimpleName();
		return getLogPath(context, userid, dir, fileName);
	}

    public static String getDeviceLogPath(Context context, String userid, String date){
        String dir = C.dir.log;
        String fileName = DeviceInfoTool.class.getSimpleName();
        return getLogPath(context, userid, dir, fileName, date);
    }

	public static void writeDeviceToolLog(final Context context, final String content, String userid){
        String dir = C.dir.log;
        String fileName = DeviceInfoTool.class.getSimpleName();
        writeLog2Sdcard(context, userid, content, dir, fileName);
    }

    public static void clearDeviceLogBeforeDay(String userid){
        String dir = C.dir.log;
        String fileName = DeviceInfoTool.class.getSimpleName();
        clearLogBeforeDay(dir, fileName, userid);
    }

	public static String getGpsLogPath(Context context, String userid){
		String dir = C.dir.log;
		String fileName = GpsTool.class.getSimpleName();
		return getLogPath(context, userid, dir, fileName);
	}

    public static String getGpsLogPath(Context context, String userid, String date){
        String dir = C.dir.log;
        String fileName = GpsTool.class.getSimpleName();
        return getLogPath(context, userid, dir, fileName, date);
    }

    public static void writeGpsToolLog(final Context context, final String content, String userid){
        String dir = C.dir.log;
        String fileName = GpsTool.class.getSimpleName();
        writeLog2SdcardDebug(context, userid, content, dir, fileName);
    }

    public static void clearGpsLogBeforeDay(String userid){
        String dir = C.dir.log;
        String fileName = GpsTool.class.getSimpleName();
        clearLogBeforeDay(dir, fileName, userid);
    }

	public static String getBaiduLogPath(Context context, String userid){
		String dir = C.dir.log;
		String fileName = C.BAIDU_DEBUG;
		return getLogPath(context, userid, dir, fileName);
	}

    public static String getBaiduLogPath(Context context, String userid, String date){
        String dir = C.dir.log;
        String fileName = C.BAIDU_DEBUG;
        return getLogPath(context, userid, dir, fileName, date);
    }

    public static void writeBaiduLog(final Context context, final String content, String userid){
        String dir = C.dir.log;
        String fileName = C.BAIDU_DEBUG;
        writeLog2SdcardDebug(context, userid, content, dir, fileName);
    }

    public static void clearBaiduLogBeforeDay(String userid){
        String dir = C.dir.log;
        String fileName = C.BAIDU_DEBUG;
        clearLogBeforeDay(dir, fileName, userid);
    }

	public static String getAmapLogPath(Context context, String userid){
		String dir = C.dir.log;
		String fileName = C.AMAP_DEBUG;
		return getLogPath(context, userid, dir, fileName);
	}

    public static String getAmapLogPath(Context context, String userid, String date){
        String dir = C.dir.log;
        String fileName = C.AMAP_DEBUG;
        return getLogPath(context, userid, dir, fileName, date);
    }

	public static void writeAmapLog(final Context context, final String content, String userid){
		String dir = C.dir.log;
		String fileName = C.AMAP_DEBUG;
		writeLog2SdcardDebug(context, userid, content, dir, fileName);
	}

	public static void clearAmapLogBeforeDay(String userid){
		String dir = C.dir.log;
		String fileName = C.AMAP_DEBUG;
		clearLogBeforeDay(dir, fileName, userid);
	}

	public static void clearLogBeforeDay(String userid){
		clearGpsLogBeforeDay(userid);
        clearAmapLogBeforeDay(userid);
		clearDeviceLogBeforeDay(userid);
	}

	public static void writeArcgisLog(final Context context, final String content, String userid){
		String dir = C.dir.log;
		String fileName = C.ARCGIS_DEBUG;
        writeLog2SdcardDebug(context, userid, content, dir, fileName);
	}

	private static final long MAX_DAY_OFFSET_SECOND = 30 * 24 * 3600; //30天
	public static void clearLogBeforeDay(final String dir, final String fileName, String userid){
        String rootPath = dir;
        if (userid != null && !userid.isEmpty()){
            rootPath = dir + userid + "/";
        }
        File root = new File(rootPath);
        if (!root.exists())
            return;

        String todayDate = DateUtils.getYMD();

        File[] childFiles = root.listFiles();
        for (File child : childFiles){
            if (child.isFile()){
                String name = child.getName();
                if (name.startsWith(fileName)){
                    int start = fileName.length() + 1;
                    int end = name.lastIndexOf(".");
                    String childDate = name.substring(start, end);
                    if (childDate != null){
                        long offset = DateUtils.getTimeOffset(childDate, todayDate, "yyyy-MM-dd");
                        if (offset / 1000 >= MAX_DAY_OFFSET_SECOND){
                            child.deleteOnExit();
                        }
                    }
                }
            }
        }
    }
}
