package com.viaccessorca.voplayerdemo.activities;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.SpannableString;
import android.text.util.Linkify;
import android.util.Log;
import android.view.KeyEvent;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.viaccessorca.voplayer.VOPlayer;
import com.viaccessorca.voplayerdemo.AppConfig;
import com.viaccessorca.voplayerdemo.Constants;
import com.viaccessorca.voplayerdemo.R;
import com.viaccessorca.voplayerdemo.Utils;
import com.viaccessorca.voplayerdemo.mediamgt.MediaDescriptionParser;
import com.viaccessorca.voplayerdemo.mediamgt.MediaItem;
import com.viaccessorca.voplayerdemo.mediamgt.StreamingMediaItem;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * Starting-point Activity for VOPlayer
 * This Activity is in charge of checking for execution rights and restrictions and
 * forwarding user to the player or browser activities.
 * It also executes the SDK benchmark if need be.
 */
public class SplashActivity extends Activity {

    /* Results */
    protected static final int RESULT_QUIT = 100;

    private static final String TAG = "SplashActivity";

    private static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;

    /**
     * Asynchronous task that runs the player benchmark in a separate thread, to avoid freezing the UI
     */
    private class RunPlayerBenchmarkAsyncTask extends AsyncTask<Void, Void, Void> {

        private static final String TAG = "RunPlayerBenchmarkATask";

        protected Void doInBackground(Void... nothing) {
            Log.d(TAG, "start benchmark");
            VOPlayer.runPlatformBenchmark(SplashActivity.this.getApplicationContext(), false, true);
            Log.d(TAG, "benchmark done");
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            if(null != playerBenchmarkDialog){
                playerBenchmarkDialog.dismiss();
                playerBenchmarkDialog = null;
                Animation scaleUp = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.scale_up);
                centerLogo.startAnimation(scaleUp);
            }
            startForwardHandler();
        }
    }


    // time in milliseconds for which the splash screen is displayed
    private static final int SPLASH_TIME_MILLIS = 2000;

    // View elements
    private Handler handler;
    private Runnable forwardToActivitiesRunnable;
    private TextView buildText;
    private TextView sdkExpirationText;

    private ImageView centerLogo;

    // Have we been called from outside the app?
    private boolean directIntent = false;
    private Intent incomingIntent = null;

    private StreamingMediaItem forwardMediaItem = null;

    private String buildVersion = null;
    private boolean qpSDKOK = false;
    private boolean bPermissionAlreadyChecked = false;

    private static final int DIALOG_LICENSE_ALTERED_ID = 1;
    private static final int DIALOG_PLAYER_BENCHMARK_ID = 2;
    private static final int DIALOG_SERVICE_VERSION_UPDATE_REQUIRED = 3;
    private static final int DIALOG_RECEIVED_MEDIA_DESCRIPTION = 4;

    private static final int REQUEST_PLAYER = 1;
    private static final int REQUEST_BROWSER = 2;


    private AppConfig appConfig = null;

    private ProgressDialog playerBenchmarkDialog = null;

    private String incomingMediaDescName = null;
    private String incomingMediaDescData = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.v(TAG, "onCreate");
        super.onCreate(savedInstanceState);

        String board = Build.BOARD;
        Log.v(TAG, "Board = " + board);
        if(board.equals("GT-P7510")) {
            Log.w(TAG, "Loading OpenSLES additional libraries on Galaxy Tab 10.1");
            try {
                System.loadLibrary("wilhelm");
                System.loadLibrary("OpenSLES");
            }
            catch(Exception e) {}
        }

        setContentView(R.layout.splash_activity);

        Bundle bundle = this.getIntent().getExtras();
        if (null != bundle && bundle.getBoolean("runFromExternalApp")) {
            String displayName = "External Stream";

            forwardMediaItem = new StreamingMediaItem(Utils.getMD5Hash(displayName), bundle.getString(Constants.DATA_SOURCE_INTENT_SKEY), displayName, false);

            forwardMediaItem.setCompanyName(bundle.getString(Constants.VCAS_COMPANY_NAME_INTENT_SKEY));
            forwardMediaItem.setBootAddress(bundle.getString(Constants.VCAS_BOOT_ADDRESS_INTENT_SKEY));
            forwardMediaItem.setDrmAgentType(bundle.getString(Constants.DRM_AGENT_TYPE_SKEY));
            forwardMediaItem.setDRMLicenseAcquisitionCustomData(bundle.getString(Constants.DRM_LICENSE_CUSTOM_DATA_SKEY));
            forwardMediaItem.setDRMLicenseAcquisitionUrl(bundle.getString(Constants.DRM_LICENSE_URL_SKEY));
            forwardMediaItem.setDRMLicenseAcquisitionUrlParameters(bundle.getString(Constants.DRM_LICENSE_URL_PARAMETERS_SKEY));
            String fullCookie = "";
            String cookies[] = bundle.getStringArray(Constants.DRM_LICENSE_COOKIE_SKEY);
            if (null != cookies) {
                for (String c: cookies) {
                    fullCookie += c + ";";
                }
                forwardMediaItem.setDRMLicenseAcquisitionCookie(fullCookie);
            }

            forwardMediaItem.setDrmPersonalizationUrl(bundle.getString(Constants.DRM_PERSONALIZATION_URL));
            forwardMediaItem.setDrmPersonalizationAppVersion(bundle.getString(Constants.DRM_PERSONALIZATION_APPVERSION));
            forwardMediaItem.setDrmPersonalizationCustomData(bundle.getString(Constants.DRM_PERSONALIZATION_CUSTOM_DATA));
            forwardMediaItem.setDrmPersonalizationCustomerID(bundle.getString(Constants.DRM_PERSONALIZATION_CUSTOMER_ID));

            forwardMediaItem.setDescriptionFilePath("directData");
        }

        // Check if Activity has been called from launcher or from somewhere else
        Uri incomingUri = this.getIntent().getData();
        if (incomingUri != null) {
            Log.d(TAG, "Incoming URI: "+ incomingUri.toString());
            Log.d(TAG, "Incoming URI scheme: "+ incomingUri.getScheme());
            if(incomingUri.getScheme().equalsIgnoreCase("vop")) {
                Log.d(TAG, "Incoming VOP description !");

                incomingMediaDescName = incomingUri.getQueryParameter("id");
                String mediaDesc =  incomingUri.getQueryParameter("desc");
                incomingMediaDescData = Uri.decode(mediaDesc);
                Log.d(TAG, "mediaDescription found: " + incomingMediaDescData);
                try {
                    forwardMediaItem =  (StreamingMediaItem)MediaDescriptionParser.readMediaItemFromXMLDesc(incomingMediaDescName, new ByteArrayInputStream(incomingMediaDescData.getBytes("UTF-8")), null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            else {
                directIntent = true;
                incomingIntent = getIntent();
            }
        }
        buildText = (TextView) findViewById(R.id.build);
        PackageInfo packageInfo;
        try {
            packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            buildVersion = packageInfo.versionName;
            if (null != buildVersion) {
                buildText.setText("Evaluation Build: " + buildVersion);
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        sdkExpirationText = (TextView) findViewById(R.id.sdkExpiration);
        if (setSDKExpirationText()) {
            // Handler that handles moving us to the next activity
            handler = new Handler();
            forwardToActivitiesRunnable = new Runnable() {
                public void run() {
                    if(null != forwardMediaItem) {
                        showDialog(DIALOG_RECEIVED_MEDIA_DESCRIPTION);
                    }
                    else {
                        if (directIntent) {
                            forwardToPlayerDirect();
                        } else {
                            forwardToBrowser();
                        }
                    }
                }
            };
        }
        centerLogo = (ImageView) findViewById(R.id.centerLogo);
    }

    private boolean setSDKExpirationText() {
        try {
            long sdkExpirationTime = (long) VOPlayer.getSDKExpirationTime(getApplicationContext());
            if (0 == sdkExpirationTime) {
                sdkExpirationText.setText("VOPlayer SDK has no expiration date.");
            } else {
                if (sdkExpirationTime > (System.currentTimeMillis() / 1000)) {
                    DateFormat df = DateFormat.getDateTimeInstance();
                    sdkExpirationText.setText("VOPlayer SDK will expire on\n" + df.format(new Date(sdkExpirationTime * 1000)));
                    sdkExpirationText.setTextColor(Color.YELLOW);
                } else {
                    sdkExpirationText.setText("WARNING: integrated VOPlayer SDK has expired !");
                    sdkExpirationText.setTextSize(20);
                    sdkExpirationText.setTextColor(Color.RED);
                }
            }
            qpSDKOK = true;
        }
        catch(java.lang.UnsatisfiedLinkError e) {
            Log.e(TAG, "Error while loading VOPlayer SDK");
            sdkExpirationText.setText("ERROR: the application could not load VOPlayer SDK!\nCheck that native libraries are present and valid in your project.");
            sdkExpirationText.setTextSize(20);
            sdkExpirationText.setTextColor(Color.RED);
            return false;
        }
        return true;
    }

    private void startForwardHandler() {
        if(handler != null && !isFinishing()) {
            handler.removeCallbacks(forwardToActivitiesRunnable);
            handler.postDelayed(forwardToActivitiesRunnable, SPLASH_TIME_MILLIS);
        }
    }

    private void forwardToPlayerDirect() {
        Log.v(TAG, "forwardToPlayerDirect");
        Intent intent = createForwardToPlayerIntent();
        startActivityForResult(intent, REQUEST_PLAYER);
        this.finish();
    }

    private void forwardToBrowser() {
        Log.v(TAG, "forwardToBrowser");
        Intent intent = new Intent(SplashActivity.this, MediaListActivity.class);
        startActivityForResult(intent, REQUEST_BROWSER);
        this.finish();
    }

    @Override
    protected void onResume() {
        Log.v(TAG, "onResume");
        super.onResume();

        if(this.qpSDKOK) {
            appConfig = AppConfig.getInstance(getApplicationContext());
            checkForApplicationRestrictions();
        }

        // don't load animation during the benchmark to avoid reducing GPU performances
        if (null == playerBenchmarkDialog) {
            Animation scaleUp = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.scale_up);
            centerLogo.startAnimation(scaleUp);
        }
    }

    @Override
    protected void onDestroy() {
        Log.v(TAG, "onDestroy");
        super.onDestroy();
        if(handler != null) {
            handler.removeCallbacks(forwardToActivitiesRunnable);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "RequestCode: " + requestCode + " ResultCode: " + resultCode);

        // Remove callbacks and finish if the result is RESULT_QUIT
        if (resultCode == RESULT_QUIT) {
            if(handler != null) {
                handler.removeCallbacks(forwardToActivitiesRunnable);
            }
            this.finish();
            return;
        }

        switch (requestCode) {
        case REQUEST_BROWSER:
            if (resultCode == RESULT_OK) {
                this.finish();
            }
            break;

        case REQUEST_PLAYER:
            if (resultCode == RESULT_OK) {
                forwardToBrowser();
            }
            break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            this.finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void forwardMediaItemToPlayer() {
        Intent fwIntent = createForwardToPlayerIntentFromMediaItemIntent(forwardMediaItem);
        startActivityForResult(fwIntent, REQUEST_PLAYER);
        this.finish();
    }

    private Intent createForwardToPlayerIntentFromMediaItemIntent(MediaItem mediaItem) {

        Intent i = new Intent();
        i.setClass(SplashActivity.this, PlayerActivity.class);
        i.setAction(Intent.ACTION_VIEW);

        Uri mediaUri = Uri.parse(mediaItem.getMediaUri());

        Utils.fillIntentWithMediaItem(i, mediaItem);

        Log.d(TAG, "starting playback for uri: " + mediaUri);
        i.setData(mediaUri);
        // Inform QP it's a native browser Call
        i.putExtra("nativeBrowserCall", true);
        i.putExtra(Constants.MEDIA_ID_SKEY, mediaItem.getMediaId());

        return i;
    }

    private Intent createForwardToPlayerIntent() {

        Intent forwardIntent;
        forwardIntent = new Intent(SplashActivity.this, PlayerActivity.class);
        forwardIntent.setData(incomingIntent.getData());

        String sKeyValue = incomingIntent.getStringExtra(Constants.AUDIO_LANGUAGE_INTENT_SKEY);
        if(null != sKeyValue) {
            forwardIntent.putExtra(Constants.AUDIO_LANGUAGE_INTENT_SKEY, sKeyValue);
        }

        int iKeyValue = incomingIntent.getIntExtra(Constants.RESUME_TIME_INTENT_IKEY, -1);
        if(iKeyValue > 0) {
            forwardIntent.putExtra(Constants.RESUME_TIME_INTENT_IKEY, iKeyValue);
        }

        sKeyValue = incomingIntent.getStringExtra(Constants.SUBTITLE_FILE_INTENT_SKEY);
        if(null != sKeyValue) {
            forwardIntent.putExtra(Constants.SUBTITLE_FILE_INTENT_SKEY, sKeyValue);
        }
        sKeyValue = incomingIntent.getStringExtra(Constants.SUBTITLE_TRACK_INTENT_SKEY);
        if(null != sKeyValue) {
            forwardIntent.putExtra(Constants.SUBTITLE_TRACK_INTENT_SKEY, sKeyValue);
        }
        iKeyValue = incomingIntent.getIntExtra(Constants.SUBTITLE_TRACKTYPE_INTENT_SKEY, 0);
        if(iKeyValue > 0) {
            forwardIntent.putExtra(Constants.SUBTITLE_TRACKTYPE_INTENT_SKEY, iKeyValue);
        }
        sKeyValue = incomingIntent.getStringExtra(Constants.VCAS_BOOT_ADDRESS_INTENT_SKEY);
        if(null != sKeyValue) {
            forwardIntent.putExtra(Constants.VCAS_BOOT_ADDRESS_INTENT_SKEY, sKeyValue);
        }
        sKeyValue = incomingIntent.getStringExtra(Constants.VCAS_COMPANY_NAME_INTENT_SKEY);
        if(null != sKeyValue) {
            forwardIntent.putExtra(Constants.VCAS_COMPANY_NAME_INTENT_SKEY, sKeyValue);
        }
        sKeyValue = incomingIntent.getStringExtra(Constants.DRM_AGENT_TYPE);
        if(null != sKeyValue) {
            forwardIntent.putExtra(Constants.DRM_AGENT_TYPE, sKeyValue);
        }
        sKeyValue = incomingIntent.getStringExtra(Constants.DRM_PERSONALIZATION_URL);
        if(null != sKeyValue) {
            forwardIntent.putExtra(Constants.DRM_PERSONALIZATION_URL, sKeyValue);
        }
        sKeyValue = incomingIntent.getStringExtra(Constants.DRM_PERSONALIZATION_APPVERSION);
        if(null != sKeyValue) {
            forwardIntent.putExtra(Constants.DRM_PERSONALIZATION_APPVERSION, sKeyValue);
        }
        sKeyValue = incomingIntent.getStringExtra(Constants.DRM_PERSONALIZATION_CUSTOM_DATA);
        if(null != sKeyValue) {
            forwardIntent.putExtra(Constants.DRM_PERSONALIZATION_CUSTOM_DATA, sKeyValue);
        }
        sKeyValue = incomingIntent.getStringExtra(Constants.DRM_LICENSE_URL_SKEY);
        if(null != sKeyValue) {
            forwardIntent.putExtra(Constants.DRM_LICENSE_URL_SKEY, sKeyValue);
        }
        sKeyValue = incomingIntent.getStringExtra(Constants.DRM_LICENSE_CUSTOM_DATA_SKEY);
        if(null != sKeyValue) {
            forwardIntent.putExtra(Constants.DRM_LICENSE_CUSTOM_DATA_SKEY, sKeyValue);
        }
        sKeyValue = incomingIntent.getStringExtra(Constants.DRM_LICENSE_COOKIE_SKEY);
        if(null != sKeyValue) {
            forwardIntent.putExtra(Constants.DRM_LICENSE_COOKIE_SKEY, sKeyValue);
        }
        sKeyValue = incomingIntent.getStringExtra(Constants.DRM_CONTENT_IDENTIFIER);
        if(null != sKeyValue) {
            forwardIntent.putExtra(Constants.DRM_CONTENT_IDENTIFIER, sKeyValue);
        }
        boolean bKeyValue = incomingIntent.getBooleanExtra(Constants.DRM_LICENSE_USE_VOSECURITYGATEWAY, false);
        forwardIntent.putExtra(Constants.DRM_LICENSE_USE_VOSECURITYGATEWAY, bKeyValue);
        return forwardIntent;
    }


    @Override
    protected void onNewIntent(Intent intent) {
        directIntent = true;
        incomingIntent = intent;
    }


    /**
     * Checks if the application is entitled to run on the current device and reacts accordingly
     */
    private void checkForApplicationRestrictions()
    {
        if(!appConfig.isConfigValid()) {
            showDialog(DIALOG_LICENSE_ALTERED_ID);
        } else {
            int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
            if (ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED == result || ConnectionResult.SERVICE_INVALID  == result){
                /* google play service version update is required for chromecast support */
                showDialog(DIALOG_SERVICE_VERSION_UPDATE_REQUIRED);
            } else {
                /* check permissions and launch benchmarks once permissions are granted */
                if (checkAndRequestPermissions()) {
                    runSDKBenchmark();
                }
            }
        }
    }


    @Override
    protected Dialog onCreateDialog(int id)
    {
        Log.d(TAG, "onCreateDialog id="+ id);
        switch(id) {
            case DIALOG_LICENSE_ALTERED_ID: {
                AlertDialog.Builder restrictionBuilder = new AlertDialog.Builder(this);
                final SpannableString invalidMessage = new SpannableString(getResources().getText(R.string.license_tempered));
                Linkify.addLinks(invalidMessage, Linkify.EMAIL_ADDRESSES);

                restrictionBuilder.setTitle(R.string.title_access_denied)
                        .setMessage(invalidMessage)
                        .setCancelable(false);
                restrictionBuilder.setNeutralButton(R.string.OK_text,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                SplashActivity.this.finish();
                            }
                        });
                return restrictionBuilder.create();
            }

            case DIALOG_PLAYER_BENCHMARK_ID: {

                playerBenchmarkDialog = new ProgressDialog(this);
                playerBenchmarkDialog.setCancelable(false);
                playerBenchmarkDialog.setTitle(R.string.wait);
                playerBenchmarkDialog.setMessage("Running player benchmark");
                playerBenchmarkDialog.setIndeterminate(true);
                playerBenchmarkDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                return playerBenchmarkDialog;
            }

            case DIALOG_SERVICE_VERSION_UPDATE_REQUIRED: {
                AlertDialog.Builder restrictionBuilder = new AlertDialog.Builder(this);
                final SpannableString invalidMessage = new SpannableString(getResources().getText(R.string.googleplayservice_upodate_required));
                Linkify.addLinks(invalidMessage, Linkify.EMAIL_ADDRESSES);

                restrictionBuilder.setTitle(R.string.title_googleplayservice_update_required)
                        .setMessage(invalidMessage)
                        .setCancelable(false);
                restrictionBuilder.setNeutralButton(R.string.OK_text,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                SplashActivity.this.finish();
                            }
                        });
                return restrictionBuilder.create();
            }

            case DIALOG_RECEIVED_MEDIA_DESCRIPTION:
                AlertDialog.Builder newMediaDescBuilder = new AlertDialog.Builder(this);
                final SpannableString dialogMessage = new SpannableString("New media description received: " + forwardMediaItem.getDisplayName());

                newMediaDescBuilder.setTitle("New media")
                        .setMessage(dialogMessage)
                        .setCancelable(false);
                newMediaDescBuilder.setNeutralButton("Store", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        storeIncomingMediaDescription();
                        forwardToBrowser();
                    }
                });
                newMediaDescBuilder.setPositiveButton("Play", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        forwardMediaItemToPlayer();
                    }
                });
                return newMediaDescBuilder.create();

            default:
                return super.onCreateDialog(id);
        }
    }

    private boolean storeIncomingMediaDescription() {
        FileOutputStream outputStream;
        String fullFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/qp3_medias/" + incomingMediaDescName + ".vop";

        try {
            File mediaDescFile = new File(fullFileName);
            if(mediaDescFile.exists()) {
                Toast.makeText(getApplicationContext(), "Error: media file " + incomingMediaDescName + " already exists !", Toast.LENGTH_SHORT).show();
                return false;
            }

            outputStream = new FileOutputStream(mediaDescFile);
            outputStream.write(incomingMediaDescData.getBytes());
            outputStream.close();
            Toast.makeText(getApplicationContext(), "Media file " + incomingMediaDescName + " successfully stored", Toast.LENGTH_SHORT).show();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_ID_MULTIPLE_PERMISSIONS: {
                // Launch benchmark just after checking permissions
                runSDKBenchmark();
                return;
            }
            default:
                break;
        }
    }

    private boolean checkAndRequestPermissions() {
        if (!bPermissionAlreadyChecked && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int permissionReadExternalStorage = ContextCompat.checkSelfPermission(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE);
            int permissionWriteExternalStorage = ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int permissionReadPhoneState = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
            List<String> listPermissionsNeeded = new ArrayList<>();
            if (permissionReadExternalStorage != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (permissionWriteExternalStorage != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (permissionReadPhoneState != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
            }
            bPermissionAlreadyChecked = true;
            if (!listPermissionsNeeded.isEmpty()) {
                ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
                return false;
            }
        }
        return true;
    }

    private void runSDKBenchmark() {
        boolean benchmarkUpToDate = VOPlayer.isPlatformBenchmarkUpToDate(SplashActivity.this.getApplicationContext());
        if(benchmarkUpToDate) {
            startForwardHandler();
            Toast.makeText(SplashActivity.this.getApplicationContext(), "Benchmark up to date", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(SplashActivity.this.getApplicationContext(), "Benchmark outdated > Run it", Toast.LENGTH_SHORT).show();
            new RunPlayerBenchmarkAsyncTask().execute();
            showDialog(DIALOG_PLAYER_BENCHMARK_ID);
        }
    }
}
