package com.wytehat.btlogger;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Formatting and escaping helpers shared by the map screen, the HTML it
 * feeds the WebView and the CSV exporter.
 *
 * These used to be private methods on MapActivity, which meant every piece
 * of code that wanted to escape a popup string or stamp a timestamp had to
 * live in that one class.
 */
public final class MapFormat {

    private MapFormat() {
    }

    public static boolean hasValue(String value) {
        return value != null && value.trim().length() > 0;
    }

    /** Human readable timestamp, or "Unknown" for a missing/zero time. */
    public static String date(long time) {
        return time <= 0
            ? "Unknown"
            : DateFormat.getDateTimeInstance().format(new Date(time));
    }

    /** Turns a raw disconnect reason into something worth showing a user. */
    public static String reason(String value) {

        if (value == null) return "Status unknown";

        if (value.indexOf("Range") >= 0) return "Out of range";

        if (value.indexOf("Battery") >= 0 || value.indexOf("Power") >= 0) {
            return "Possible dead battery";
        }

        return value;
    }

    /** Falls back to the default pin red when a stored colour is unusable. */
    public static String validColor(String value) {

        if (value != null && value.matches("#[0-9a-fA-F]{6}")) {
            return value;
        }

        return "#E53935";
    }

    public static String number(double value) {
        return String.format(Locale.US, "%.2f", value);
    }

    public static String htmlText(String value) {

        if (value == null) return "";

        return value
            .replace("&", "&amp;")
            .replace("<", "&lt;")
            .replace(">", "&gt;")
            .replace("\"", "&quot;")
            .replace("'", "&#39;");
    }

    /** Escapes a string for use inside a single-quoted JavaScript literal. */
    public static String js(String value) {

        if (value == null) return "";

        return value
            .replace("\\", "\\\\")
            .replace("'", "\\'")
            .replace("\"", "\\\"")
            .replace("\r", "\\r")
            .replace("\n", "\\n")
            .replace(" ", "\\u2028")
            .replace(" ", "\\u2029");
    }

    /** Quotes a CSV field, doubling quotes and flattening newlines. */
    public static String csv(String value) {

        if (value == null) return "\"\"";

        return "\"" +
            value
                .replace("\"", "\"\"")
                .replace("\r", " ")
                .replace("\n", " ") +
            "\"";
    }
}
