package com.dragonssh.xhttpdemo.core.logger;

import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;

import java.util.Locale;

/** A small, application-neutral log record for the public example. */
public final class LogItem implements Parcelable {
    private final Object[] args;
    private final String message;
    private final int resourceId;
    private final SkStatus.LogLevel level;
    private final long logTime;

    public LogItem(int resourceId, Object... args) {
        this(SkStatus.LogLevel.INFO, resourceId, args);
    }

    public LogItem(SkStatus.LogLevel level, int verbosityLevel, String message) {
        this(level, message);
    }

    public LogItem(SkStatus.LogLevel level, int resourceId, Object... args) {
        this.level = level;
        this.resourceId = resourceId;
        this.args = args;
        this.message = null;
        this.logTime = System.currentTimeMillis();
    }

    public LogItem(SkStatus.LogLevel level, String message) {
        this.level = level;
        this.message = message;
        this.resourceId = 0;
        this.args = null;
        this.logTime = System.currentTimeMillis();
    }

    public LogItem(SkStatus.LogLevel level, int resourceId) {
        this(level, resourceId, (Object[]) null);
    }

    private LogItem(Parcel in) {
        args = in.readArray(Object.class.getClassLoader());
        message = in.readString();
        resourceId = in.readInt();
        int levelValue = in.readInt();
        SkStatus.LogLevel parsed = SkStatus.LogLevel.getEnumByValue(levelValue);
        level = parsed != null ? parsed : SkStatus.LogLevel.INFO;
        logTime = in.readLong();
    }

    public SkStatus.LogLevel getLogLevel() {
        return level;
    }

    public long getLogtime() {
        return logTime;
    }

    public String getMessage() {
        return message;
    }

    public String getString(Context context) {
        if (message != null) {
            return message;
        }
        if (context == null || resourceId == 0) {
            return String.format(Locale.US, "Log resource %d", resourceId);
        }
        return args == null ? context.getString(resourceId) : context.getString(resourceId, args);
    }

    @Override
    public String toString() {
        return getString(null);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeArray(args);
        dest.writeString(message);
        dest.writeInt(resourceId);
        dest.writeInt(level.getInt());
        dest.writeLong(logTime);
    }

    public static final Creator<LogItem> CREATOR = new Creator<LogItem>() {
        @Override
        public LogItem createFromParcel(Parcel in) {
            return new LogItem(in);
        }

        @Override
        public LogItem[] newArray(int size) {
            return new LogItem[size];
        }
    };
}
