package com.android.launcher3.util;

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.util.Log;


import com.android.launcher3.BuildConfig;
import com.elvishew.xlog.LogLevel;
import com.elvishew.xlog.XLog;
import com.elvishew.xlog.flattener.Flattener;
import com.elvishew.xlog.flattener.Flattener2;
import com.elvishew.xlog.printer.Printer;
import com.elvishew.xlog.printer.file.FilePrinter;
import com.elvishew.xlog.printer.file.backup.NeverBackupStrategy;
import com.elvishew.xlog.printer.file.clean.FileLastModifiedCleanStrategy;
import com.elvishew.xlog.printer.file.naming.DateFileNameGenerator;

import java.io.File;

public class Logger {

    public static final int MAX_TIME = 2 * 24 * 3600;
    public static final boolean DEBUGGABLE = BuildConfig.DEBUG;

    private static boolean init = false;

    public static void init(Context application) {
        Printer filePrinter = new FilePrinter                      // Printer that print the log to the file system
                .Builder(application.getExternalCacheDir().getAbsolutePath() + File.separator + "xlog" + File.separator)                              // Specify the path to save log file
                .fileNameGenerator(new DateFileNameGenerator())        // Default: ChangelessFileNameGenerator("log")
                .backupStrategy(new NeverBackupStrategy())             // Default: FileSizeBackupStrategy(1024 * 1024)
                .cleanStrategy(new FileLastModifiedCleanStrategy(MAX_TIME))     // Default: NeverCleanStrategy()
                .flattener(new CustomFlattener())                          // Default: DefaultFlattener
                .build();


        XLog.init(LogLevel.ALL, filePrinter);
        init = true;
    }


    public static void d(String TAG, String info) {
        if (init) {
            XLog.d(info);
        }

        if (!DEBUGGABLE)
            return;
        Log.d(TAG, info);
    }

    public static void i(String TAG, String info) {
        if (init) {
            XLog.i(info);
        }

        if (!DEBUGGABLE)
            return;
        Log.i(TAG, info);
    }

    public static void e(String TAG, String info) {
        if (init) {
            XLog.e(info);
        }

        if (!DEBUGGABLE)
            return;
        Log.e(TAG, info);
    }

    public static void v(String TAG, String info) {
        if (init) {
            XLog.v(info);
        }

        if (!DEBUGGABLE)
            return;
        Log.v(TAG, info);
    }


    public static class CustomFlattener implements Flattener2 {


        @Override
        public CharSequence flatten(long timeMillis, int logLevel, String tag, String message) {
            return String.format("time = %s level = %d TAG = %s MSG:%s", TimeUtils.getTime(timeMillis, TimeUtils.DATE_FORMAT_ALL), logLevel, tag, message);
        }
    }
}
