package com.insidesecure.drm.android.reference.tools;

import android.util.Log;
import com.insidesecure.drmagent.DRMLogCallback;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public final class DRMLogProvider implements DRMLogCallback {

    private static final String  TAG = DRMLogProvider.class.getSimpleName();
    private static final int MAX_LAST_LOGS = 100;

    private static DRMLogProvider instance = null;

    private BlockingQueue<DRMLogEntry> mDRMLogEntriesQueue;
    private List<DRMLogEntry> mDRMLogEntries;

    private DRMLogProvider() {
        mDRMLogEntries = new ArrayList<>(MAX_LAST_LOGS);
        mDRMLogEntriesQueue = new LinkedBlockingQueue<>(MAX_LAST_LOGS);
    }

    public static synchronized DRMLogProvider getInstance() {
        if (instance == null) {
            instance = new DRMLogProvider();
        }
        return instance;
    }

    public List<DRMLogEntry> getLastLogs() {
        return mDRMLogEntries;
    }

    @Override
    public void processDRMLogEntries(List<DRMLogEntry> drmLogEntries) {
        for (DRMLogEntry drmLogEntry : drmLogEntries) {
            try {

                mDRMLogEntriesQueue.put(new DRMLogEntry(drmLogEntry));

                if (mDRMLogEntriesQueue.size() >= MAX_LAST_LOGS) {
                    mDRMLogEntries.clear();
                    mDRMLogEntriesQueue.drainTo(mDRMLogEntries, MAX_LAST_LOGS);
                }
            } catch (InterruptedException e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }
}
