package com.facebook.internal.metrics;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.SystemClock;
import com.facebook.internal.Utility;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import ඓ.K.K.K.C1293;

public class MetricsUtil {
    public final String CLASS_TAG = "internal.MetricsUtil";
    public final String STARTUP_METRICS_PREFERENCES = "MetricsUtil";
    public final String TIME_DIFFERENCE_BASE_PREF = "time_difference";
    public WeakReference<Context> ctx;
    public MetricsUtil metricsUtil;
    public HashMap<Tag, Long> taggedStartTimer = new HashMap<>();

    public MetricsUtil(Context context) {
        this.ctx = new WeakReference<>(context);
    }

    private void updateLastTimeDifferenceFor(Tag tag, long j) {
        if (this.ctx.get() == null) {
            Utility.logd("internal.MetricsUtil", "updateLastTimeDifferenceFor: Context is null");
            return;
        }
        SharedPreferences.Editor edit = this.ctx.get().getSharedPreferences("MetricsUtil", 0).edit();
        StringBuilder r1 = C1293.m3416("time_difference");
        r1.append(tag.getSuffix());
        edit.putLong(r1.toString(), j).apply();
    }

    public synchronized MetricsUtil getInstance(Context context) {
        if (this.metricsUtil == null) {
            this.metricsUtil = new MetricsUtil(context);
            return this.metricsUtil;
        }
        return this.metricsUtil;
    }

    public long getLastTimeDifferenceFor(Tag tag) {
        if (this.ctx.get() == null) {
            Utility.logd("internal.MetricsUtil", "getLastTimeDifferenceFor: Context is null");
            return -1;
        }
        SharedPreferences sharedPreferences = this.ctx.get().getSharedPreferences("MetricsUtil", 0);
        StringBuilder r3 = C1293.m3416("time_difference");
        r3.append(tag.getSuffix());
        return sharedPreferences.getLong(r3.toString(), -1);
    }

    public void startMeasureFor(Tag tag) {
        this.taggedStartTimer.put(tag, Long.valueOf(SystemClock.elapsedRealtime()));
    }

    public void stopMeasureFor(Tag tag) {
        long elapsedRealtime = SystemClock.elapsedRealtime();
        if (this.taggedStartTimer.containsKey(tag)) {
            long longValue = elapsedRealtime - this.taggedStartTimer.get(tag).longValue();
            this.taggedStartTimer.remove(tag);
            updateLastTimeDifferenceFor(tag, longValue);
        }
    }
}
