package com.avg.zaap.crashlibrary.provider.memory;

import android.content.Context;
import android.os.Debug;
import android.support.annotation.NonNull;

import com.avg.zaap.crashlibrary.core.logger.CrashLogger;
import com.avg.zaap.crashlibrary.provider.CrashProviderException;
import com.avg.zaap.crashlibrary.provider.ICrashSyncProvider;

import java.io.File;
import java.io.IOException;

/**
 * Synchronous provider for memory heap.
 * <p>
 * Created by marek.osvald on 8. 4. 2016.
 */
public class MemoryHeapProvider implements ICrashSyncProvider {

    private static final String TAG = MemoryHeapProvider.class.getSimpleName();
    private static final String FILE_NAME = "dump.dalvik.hprof";

    /**
     * Default constructor.
     */
    public MemoryHeapProvider() {
    }

    /**
     * Parametric constructor. Not used.
     *
     * @param context android context
     */
    @SuppressWarnings("unused")
    public MemoryHeapProvider(@SuppressWarnings("UnusedParameters") Context context) {
    }

    @Override
    public String provideData(@NonNull final String directory) throws CrashProviderException {
        final String filePath = directory + File.separatorChar + FILE_NAME;

        try {
            Debug.dumpHprofData(filePath);
        } catch (UnsupportedOperationException ex) {
            CrashLogger.e(TAG, ex.getMessage());
            throw new CrashProviderException("Heap dumps not supported.", ex);
        } catch (IOException ex) {
            CrashLogger.e(TAG, ex.getMessage());
            throw new CrashProviderException("Unable to dump heap.", ex);
        }

        return filePath;
    }

}
