package com.insidesecure.drm.android.reference.xoplayer.activities.helpers;

import android.os.*;
import com.insidesecure.drmagent.mediaplayer.*;

/**
 * @author
 */
public class FrameRateCalculator
{
    private MediaPlayer mMediaPlayer;
    private final FrameRateReportCallback mFrameRateReportCallback;
    private CodecCounters mCodecCounters;
    int mLastRenderedOutputBufferCount;
    private boolean mKeepRunning = true;

    public interface FrameRateReportCallback
    {
        public void framesPerSecond(int frameRate);
    }

    public FrameRateCalculator(final MediaPlayer mediaPlayer, final Looper looper, FrameRateReportCallback frameRateReportCallback )
    {
        mMediaPlayer = mediaPlayer;
        mFrameRateReportCallback = frameRateReportCallback;
        mCodecCounters = new CodecCounters();

        // Main work is already on the main looper, so why not contiue that
        final Handler handler = new Handler(looper);
        final Runnable frameCalculatorRunnable = new Runnable()
        {
            @Override
            public void run()
            {
                calculateCurrentRenderedFramePerSecond();
                if (mKeepRunning)
                {
                    handler.postDelayed(this, 1000);
                }
            }
        };

        handler.postDelayed(frameCalculatorRunnable, 1000);
    }

    private void calculateCurrentRenderedFramePerSecond()
    {
        if (mMediaPlayer.isPlaying())
        {
            mMediaPlayer.updateCodecCounters(mCodecCounters);
            if(mLastRenderedOutputBufferCount != 0)
            {
                //Updating the Content Info layout
                final int framesPerSecond = mCodecCounters.mRenderedOutputBufferCount - mLastRenderedOutputBufferCount;
                mFrameRateReportCallback.framesPerSecond(framesPerSecond);
            }
            mLastRenderedOutputBufferCount = mCodecCounters.mRenderedOutputBufferCount;
        }
    }

    public void shutdown()
    {
        mKeepRunning = false;
    }

}
