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

import android.annotation.TargetApi;
import android.app.*;
import android.content.*;
import android.os.*;
import android.util.Log;
import android.widget.Toast;
import com.insidesecure.drm.android.reference.*;
import com.insidesecure.drm.android.reference.loaders.*;
import com.insidesecure.drm.android.reference.services.DownloadService;
import com.insidesecure.drmagent.*;
import com.insidesecure.drm.android.reference.xoplayer.R;

/**
 * @author
 */
@TargetApi(11)
public abstract class AbstractDRMActivity extends Activity implements DRMContentLoaderListener
{
    public static String TAG = "AbstractDRMActivity";

    DownloadService mDownloadService;
    boolean mDownloadServiceBound = false;

    private PlaybackInfo mPlaybackInfo;
    
    private DRMContent mDRMContent;
    private DRMAgent mDRMAgent;

    private ProgressDialog mLoadingDialog;

    protected void dismissLoadingDialog()
    {
        if (mLoadingDialog.isShowing())
        {
            mLoadingDialog.dismiss();
        }
    }

    protected void setLoadingDialogText(String message)
    {
        if (mLoadingDialog.isShowing())
        {
            mLoadingDialog.setMessage(message);
        }
    }

    @Override
    protected void onCreate(Bundle bundle)
    {
        super.onCreate(bundle);

        try
        {
            mDRMAgent = DRMAgentDelegate.initialize(AbstractDRMActivity.this);
        }

        catch (Exception exception)
        {
            Toast.makeText(this, exception.getMessage(), Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        final Bundle extras = getIntent().getExtras();

        if (extras != null)
        {
            mPlaybackInfo = (PlaybackInfo) extras.get(Constants.INTENT_EXTRA_CONTENT_PLAYBACK_INFO);
            if (mPlaybackInfo != null)
            {
                if (mDRMContent == null)
                {
                    mLoadingDialog = Tools.createSimpleProgressDialog(this, getText(R.string.dialog_title), getText(R.string.dialog_text_loading));

                    // Enable cancelation (back-button) on the dialog too
                    mLoadingDialog.setCancelable(true);
                    mLoadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener()
                    {
                        @Override
                        public void onCancel(final DialogInterface dialogInterface)
                        {
                            Log.d(TAG, "Cancel for loading dialog specified... should finish ...");
                            AbstractDRMActivity.this.finish();
                        }
                    });
                    mLoadingDialog.show();
                    
                    getLoaderManager().initLoader(DRMContentAsyncTaskLoader.ID, extras,new DRMContentAsyncTaskLoader.DRMContentLoaderCallbacks(AbstractDRMActivity.this,this)).forceLoad();
                }
            }
        }

        if (!mDownloadServiceBound)
        {
            Intent intent = new Intent(this, DownloadService.class);
            bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        }

    }

    @Override
    protected void onResume()
    {
        super.onResume();

        //
        if (mDRMAgent == null || !mDRMAgent.isInitialized())
        {
            // Always retrieve the instance
            mDRMAgent = DRMAgentDelegate.getDRMAgentInstance(AbstractDRMActivity.this);
        }

    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();

        if (mDownloadServiceBound)
        {
            unbindService(mConnection);
        }

        if (mDRMContent != null && mDRMContent.getDRMContentState() != DRMContentState.RELEASED)
        {
            mDRMContent.release();
            mDRMContent = null;
        }

        DRMAgentDelegate.uninitialize();

    }

    protected final DRMAgent getDRMAgent()
    {
        if (mDRMAgent == null || !mDRMAgent.isInitialized())
        {
            mDRMAgent = DRMAgentDelegate.getDRMAgentInstance(AbstractDRMActivity.this);
        }

        return mDRMAgent;
    }

    public final void onDRMContentInstanceCreated(final DRMContent drmContent) { mDRMContent = drmContent; onDRMContentInstanceCreatedInternal(drmContent);}
    protected void onDRMContentInstanceCreatedInternal(final DRMContent drmContent) {}

    protected PlaybackInfo getPlaybackInfo()
    {
        return mPlaybackInfo;
    }

    protected final DRMContent getDRMContent()
    {
        Assertions.checkNotNull(mDRMContent,"No DRM instance available, check your logic");
        return mDRMContent;
    }

    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection()
    {
        public void onServiceConnected(ComponentName className, IBinder service)
        {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            Log.d(TAG,"Download service connected");
            DownloadService.DownloadServiceBinder binder = (DownloadService.DownloadServiceBinder) service;
            mDownloadService = binder.getService();
            mDownloadServiceBound = true;
            downloadServiceConnected();
        }

        public void onServiceDisconnected(ComponentName arg0)
        {
            Log.d(TAG,"Download service disconnected");
            mDownloadServiceBound = false;
            mDownloadService = null;
            downloadServiceDisconnected();
        }
    };

    protected void downloadServiceDisconnected()
    {
    }

    protected void downloadServiceConnected()
    {
    }


}
