package com.xypower.common;

import android.util.Log;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;

public class LogcatHandler extends Handler {

    public LogcatHandler(String tag) {
        mTag = tag;
    }

    private String mTag = null;

    private static final int TAG_MAX_LENGTH = 23;

    static String getLevelName(int level) {
        switch (level) {
            case 1:
                return "VERY VERBOSE";
            case Log.VERBOSE:
                return "VERBOSE";
            case Log.DEBUG:
                return "DEBUG";
            case Log.INFO:
                return "INFO";
            case Log.WARN:
                return "WARN";
            case Log.ERROR:
                return "ERROR";
            case Log.ASSERT:
                return "ASSERT";
            default:
                return "UNKNOWN";
        }
    }

    static int levelFromLevel(Level level) {
        int levelInt = level.intValue();
        if (levelInt >= 1000) {
            return Log.ERROR;
        } else if (levelInt >= 900) {
            return Log.WARN;
        } else if (levelInt >= 700) {
            return Log.INFO;
        } else if (levelInt >= 500) {
            return Log.DEBUG;
        } else {
            return Log.VERBOSE;
        }
    }

    static Level levelFromLevel(int level) {
        switch (level) {
            case 1:
                return Level.FINEST;
            case Log.VERBOSE:
                return Level.FINER;
            case Log.DEBUG:
                return Level.FINE;
            case Log.INFO:
                return Level.INFO;
            case Log.WARN:
                return Level.WARNING;
            case Log.ERROR:
                return Level.SEVERE;
            case Log.ASSERT:
                return Level.SEVERE;
            default:
                return Level.FINE;
        }
    }

    @Override public void publish(LogRecord record) {
        if (record == null || !super.isLoggable(record)) {
            return;
        }

        String tag = tagFromLoggerName(record.getLoggerName());

        int level = levelFromLevel(record.getLevel());

        Log.println(level, mTag, record.getMessage());
        if (record.getThrown() != null) {
            Log.println(level, mTag, Log.getStackTraceString(record.getThrown()));
        }
    }

    @Override public void flush() {}

    @Override public void close() throws SecurityException {}

    private String tagFromLoggerName(String name) {
        if (name == null) {
            return "";
        }

        if (name.length() > TAG_MAX_LENGTH) {
            return name.substring(name.length() - TAG_MAX_LENGTH, name.length());
        } else {
            return name;
        }
    }

}
