package com.viaccessorca.voplayerdemo.activities;

import android.app.Activity;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.viaccessorca.voplayerdemo.Constants;
import com.viaccessorca.voplayerdemo.R;
import com.viaccessorca.voplayerdemo.drm.DrmManager;

import java.util.concurrent.TimeUnit;

public class DrmManagerActivity extends Activity implements View.OnClickListener
{
    private static final String TAG = "DrmManagerActivity";

    private boolean isDestroyed = false;

    private LinearLayout mNotificationLayout = null;
    private ProgressBar mNotificationWheel = null;
    private TextView mNotificationText = null;
    private ColorStateList mOldColors = null;
    private Uri mInputUri = null;

    private DRMInfoHandler mDRMInfoHandler = null;
    private DrmManager.DRMActionPooler poolerExecutor = null;

    private TextView mTextViewInfo = null;
    private String mDrmAgentType = null;
    private EditText mEditPersoUrl = null;
    private EditText mEditPersoAppVersion = null;
    private EditText mEditPersoCustomData = null;

    private EditText mEditLicenseAcquisitionCustomData = null;
    private EditText mEditLicenseAcquisitionUrl = null;
    private EditText mEditLicenseAcquisitionUrlParameters = null;
    private EditText mEditLicenseAcquisitionCookie = null;

    private Button mButtonPerso = null;
    private Button mButtonDeletePerso = null;
    private Button mButtonAcquireRights = null;
    private Button mButtonDeleteRights = null;
    private Button mButtonDeleteStore = null;

    private String mLastErrorMsg = null;
    private String mStreamUrl = null;
    private String mLicenseContentId = null;
    private boolean mLicenseUseSecurityGateway = false;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.drmmanager_activity);
        mNotificationLayout = (LinearLayout)findViewById(R.id.processingLayout);
        mNotificationWheel = (ProgressBar) findViewById(R.id.notificationWheel);
        mNotificationText = (TextView) findViewById(R.id.notificationText);

        //retrieve all fields in the layout
        mTextViewInfo = (TextView) findViewById(R.id.drmInfo);
        mEditPersoUrl = (EditText) findViewById(R.id.editPersoUrl);
        mEditPersoAppVersion = (EditText) findViewById(R.id.editPersoAppVersion);
        mEditPersoCustomData = (EditText) findViewById(R.id.editPersoCustomData);
        mEditLicenseAcquisitionCustomData = (EditText) findViewById(R.id.editLicenseAcquisitionCustomData);
        mEditLicenseAcquisitionUrl = (EditText) findViewById(R.id.editLicenseAcquisitionUrl);
        mEditLicenseAcquisitionUrlParameters = (EditText) findViewById(R.id.editLicenseAcquisitionUrlParameters);
        mEditLicenseAcquisitionCookie = (EditText) findViewById(R.id.editLicenseAcquisitionCookie);

        //save default text color
        mOldColors =  mNotificationText.getTextColors(); //save original colors

        //retrieve buttons
        mButtonPerso = (Button) findViewById(R.id.personalizeButton);
        mButtonPerso.setOnClickListener(this);
        mButtonDeletePerso = (Button) findViewById(R.id.deletePersoButton);
        mButtonDeletePerso.setOnClickListener(this);
        mButtonAcquireRights = (Button) findViewById(R.id.acquireRightsButton);
        mButtonAcquireRights.setOnClickListener(this);
        mButtonDeleteRights = (Button) findViewById(R.id.deleteRightsButton);
        mButtonDeleteRights.setOnClickListener(this);
        mButtonDeleteStore = (Button) findViewById(R.id.deleteStoreButton);
        mButtonDeleteStore.setOnClickListener(this);

        //parse intent (stream uri + DRM parameters)
        Intent intent = getIntent();
        mInputUri = intent.getData();
        mDrmAgentType = intent.getStringExtra(Constants.DRM_AGENT_TYPE);
        String persoUrl = intent.getStringExtra(Constants.DRM_PERSONALIZATION_URL);
        String persoAppVersion = intent.getStringExtra(Constants.DRM_PERSONALIZATION_APPVERSION);
        String persoCustomData = intent.getStringExtra(Constants.DRM_PERSONALIZATION_CUSTOM_DATA);
        String licenseAcqUrl = intent.getStringExtra(Constants.DRM_LICENSE_URL_SKEY);
        String licenseAcqUrlParams = intent.getStringExtra(Constants.DRM_LICENSE_URL_PARAMETERS_SKEY);
        String licenseAcqCustomData = intent.getStringExtra(Constants.DRM_LICENSE_CUSTOM_DATA_SKEY);
        String licenseAcqCookie = intent.getStringExtra(Constants.DRM_LICENSE_COOKIE_SKEY);
        mLicenseContentId = intent.getStringExtra(Constants.DRM_CONTENT_IDENTIFIER);
        mLicenseUseSecurityGateway = intent.getBooleanExtra(Constants.DRM_LICENSE_USE_VOSECURITYGATEWAY, false);

        if (null != persoUrl){
            mEditPersoUrl.setText(persoUrl);
        }
        if (null != persoAppVersion){
            mEditPersoAppVersion.setText(persoAppVersion);
        }
        if (null != persoCustomData){
            mEditPersoCustomData.setText(persoCustomData);
        }
        if (null != licenseAcqUrl){
            mEditLicenseAcquisitionUrl.setText(licenseAcqUrl);
        }
        if (null != licenseAcqUrlParams){
            mEditLicenseAcquisitionUrlParameters.setText(licenseAcqUrlParams);
        }
        if (null != licenseAcqCustomData){
            mEditLicenseAcquisitionCustomData.setText(licenseAcqCustomData);
        }
        if (null != licenseAcqCookie){
            mEditLicenseAcquisitionCookie.setText(licenseAcqCookie);
        }
        setTitle(mInputUri.getLastPathSegment());
        mStreamUrl = mInputUri.toString();

        //create threads to handle DRM info
        mDRMInfoHandler = new DRMInfoHandler();

        // Create the ThreadPollerExecutor
        poolerExecutor = new DrmManager.DRMActionPooler(getApplicationContext(), mDRMInfoHandler);

        //fill info section
        updateControlsVisibility();
        requestForRightsInfo();
    }

    @Override
    public void onDestroy() {
        // Wait for all of executor to finish
        poolerExecutor.shutdown();

        try {
            if (!poolerExecutor.awaitTermination(10, TimeUnit.SECONDS)) {
                // pool didn't terminate after the first try
                poolerExecutor.shutdownNow();
            }
        } catch (InterruptedException ex) {
            poolerExecutor.shutdownNow();
        }
        isDestroyed = true;
        super.onDestroy();
    }

    public void onClick(View v) {
        if( mButtonPerso == v ) {
            performDrmAction(DrmManager.ActionType.PERSO);
        }else if( mButtonDeletePerso == v ) {
            performDrmAction(DrmManager.ActionType.DELETE_PERSO);
        }else if(mButtonAcquireRights == v) {
            performDrmAction(DrmManager.ActionType.ACQUIRE_RIGHTS);
        }else if(mButtonDeleteRights == v) {
            performDrmAction(DrmManager.ActionType.DELETE_RIGHTS);
        }else if(mButtonDeleteStore == v) {
            performDrmAction(DrmManager.ActionType.DELETE_STORE);
        }
    }

    private void requestForRightsInfo(){
        if (mDrmAgentType.equals(Constants.DRM_AGENT_TYPE_PLAYREADY) ||
                mDrmAgentType.equals(Constants.DRM_AGENT_TYPE_VODRM)) {
            performDrmAction(DrmManager.ActionType.GET_RIGHTS_INFO);
        }
    }

    private void updateControlsVisibility(){
        if (mDrmAgentType.equals(Constants.DRM_AGENT_TYPE_PLAYREADY)||
                mDrmAgentType.equals(Constants.DRM_AGENT_TYPE_VODRM)) {
            mButtonDeleteStore.setVisibility(View.GONE);
        }else if (mDrmAgentType.equals(Constants.DRM_AGENT_TYPE_WIDEVINE)) {
            mButtonPerso.setVisibility(View.GONE);
            mButtonDeletePerso.setVisibility(View.GONE);
            mButtonDeleteRights.setVisibility(View.GONE);
            mEditPersoUrl.setVisibility(View.GONE);
            mEditPersoAppVersion.setVisibility(View.GONE);
            mEditPersoCustomData.setVisibility(View.GONE);
        }
    }

    private void performDrmAction(DrmManager.ActionType type){
        Log.d(TAG, "performDrmAction: " + type);
        DrmManager.ActionParams params = new DrmManager.ActionParams();
        params.actionType = type;
        params.contentUrl = mStreamUrl;
        params.drmAgentType = mDrmAgentType;
        params.useVOSecurityGateWay = mLicenseUseSecurityGateway;
        params.licenseContentId = mLicenseContentId;

        if (0 < mEditPersoUrl.getText().length()){
            params.persoUrl = mEditPersoUrl.getText().toString();
        }
        if (0 < mEditPersoAppVersion.getText().length()){
            params.persoAppVersion = mEditPersoAppVersion.getText().toString();
        }
        if (0 < mEditPersoCustomData.getText().length()){
            params.persoCustomData = mEditPersoCustomData.getText().toString();
        }
        if (0 < mEditLicenseAcquisitionUrl.getText().length()){
            params.licenseAcquisitionUrl = mEditLicenseAcquisitionUrl.getText().toString();
        }
        if (0 < mEditLicenseAcquisitionUrlParameters.getText().length()){
            params.licenseAcquisitionUrlParameters = mEditLicenseAcquisitionUrlParameters.getText().toString();
        }
        if (0 < mEditLicenseAcquisitionCustomData.getText().length()){
            params.licenseAcquisitionCustomData = mEditLicenseAcquisitionCustomData.getText().toString();
        }
        if (0 < mEditLicenseAcquisitionCookie.getText().length()){
            String[] cookies = new String[1];
            params.licenseAcquisitionCookie = mEditLicenseAcquisitionCookie.getText().toString();
        }

        poolerExecutor.submitDrmTask(params);
    }

    private class DRMInfoHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            if (DrmManagerActivity.this.isDestroyed) {
                Log.d(TAG, "DRMInfoHandler.handleMessage: activity destroyed");
                return;
            }

            DrmManager.NotificationParams params = (DrmManager.NotificationParams)msg.obj;
            switch(params.notificationType){
            case DISPLAY_ERROR:
                mLastErrorMsg = params.text;
                displayErrorMessage();
                break;
            case ACQUIRE_RIGHTS_START:
                resetError();
                mNotificationText.setText("Acquire rights...");
                mNotificationLayout.setVisibility(View.VISIBLE);
                break;
            case ACQUIRE_RIGHTS_DONE:
                mNotificationText.setText("Acquire rights done!");
                mNotificationLayout.setVisibility(View.GONE);
                requestForRightsInfo();
                break;
            case DELETE_RIGHTS_START:
                resetError();
                mNotificationText.setText("Delete rights...");
                mNotificationLayout.setVisibility(View.VISIBLE);
                break;
            case DELETE_RIGHTS_DONE:
                mNotificationText.setText("Delete rights done!");
                mNotificationLayout.setVisibility(View.GONE);
                requestForRightsInfo();
                break;
            case PERSO_START:
                resetError();
                mNotificationText.setText("Perso...");
                mNotificationLayout.setVisibility(View.VISIBLE);
                break;
            case PERSO_DONE:
                mNotificationText.setText("Perso done!");
                mNotificationLayout.setVisibility(View.GONE);
                requestForRightsInfo();
                break;
            case DELETE_PERSO_START:
                resetError();
                mNotificationText.setText("Delete Perso...");
                mNotificationLayout.setVisibility(View.VISIBLE);
                break;
            case DELETE_PERSO_DONE:
                mTextViewInfo.setText("none");
                mNotificationText.setText("Delete Perso done!");
                mNotificationLayout.setVisibility(View.GONE);
                requestForRightsInfo();
                break;
            case GET_RIGHTS_INFO_START:
                resetError();
                mNotificationText.setText("Get rights Info...");
                mNotificationLayout.setVisibility(View.VISIBLE);
                break;
            case GET_RIGHTS_INFO_DONE:
                mTextViewInfo.setText(params.text);
                mNotificationText.setText("Get Rights Info done!");
                mNotificationLayout.setVisibility(View.GONE);
                break;
            case DELETE_STORE_START:
                mTextViewInfo.setText(params.text);
                mNotificationText.setText("Delete store...");
                mNotificationLayout.setVisibility(View.VISIBLE);
                break;
            case DELETE_STORE_END:
                mTextViewInfo.setText(params.text);
                mNotificationText.setText("Delete store done!");
                mNotificationLayout.setVisibility(View.GONE);
                break;
            default:
                break;
            }
        }
    };

    private void displayErrorMessage() {
        if (null != mLastErrorMsg){
            mNotificationWheel.setVisibility(View.GONE);
            mNotificationText.setText(mLastErrorMsg);
            mNotificationText.setTextColor(getResources().getColor(R.color.red));
            mNotificationLayout.setVisibility(View.VISIBLE);
            mLastErrorMsg = null;
        }
    }

    private void resetError() {
        mLastErrorMsg = null;
        mNotificationWheel.setVisibility(View.VISIBLE);
        mNotificationText.setTextColor(mOldColors);
    }
}
