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

import android.annotation.TargetApi;
import android.app.LoaderManager;
import android.content.*;
import android.os.Bundle;
import android.util.Log;
import com.insidesecure.drm.android.reference.Constants;
import com.insidesecure.drm.android.reference.DRMAgentDelegate;
import com.insidesecure.drm.android.reference.activities.PlaybackInfo;
import com.insidesecure.drm.android.reference.entitlements.URLRewritingPlayReadyEntitlementDelegate;
import com.insidesecure.drmagent.DRMContent;

@TargetApi(11)
public class DRMContentAsyncTaskLoader extends AsyncTaskLoader<DRMContent>
{

    public static final String TAG = DRMContentAsyncTaskLoader.class.getSimpleName();

    // ID is needed for method initLoader in LoaderManager
    public static final int ID = 1;

    private PlaybackInfo mPlaybackInfo;

    public DRMContentAsyncTaskLoader(Context context, Bundle args)
    {
        super(context);

        mPlaybackInfo = (PlaybackInfo) args.get(Constants.INTENT_EXTRA_CONTENT_PLAYBACK_INFO);
    }

    @Override
    public DRMContent loadInBackground()
    {
        try
        {
            Log.d(TAG,"Loading DRM content instance");
            final DRMContent drmContent = DRMAgentDelegate.getDRMContent(getContext(), mPlaybackInfo.mContentLocation, mPlaybackInfo.mDRMContentFormat, mPlaybackInfo.mDRMScheme);
            drmContent.setCustomData(mPlaybackInfo.mCustomData);
            drmContent.setLicenseAcquisitionURL(mPlaybackInfo.mLicenseAcquisitionURL != null ? mPlaybackInfo.mLicenseAcquisitionURL.toString() : null);
            Log.d(TAG,"DRM content instance loaded");
            return drmContent;
        }
        catch (Exception e)
        {
            Log.e(TAG, "Error while loading descriptor: " + e.getMessage(), e);
            return null;
        }
    }

    public static class DRMContentLoaderCallbacks implements LoaderManager.LoaderCallbacks<DRMContent>
    {
        private Context mContext;
        private final DRMContentLoaderListener mDRMContentLoaderListener;

        public DRMContentLoaderCallbacks(final Context mContext, final DRMContentLoaderListener drmContentLoaderListener)
        {
            this.mContext = mContext;
            mDRMContentLoaderListener = drmContentLoaderListener;
        }

        @Override
        public Loader<DRMContent> onCreateLoader(int id, Bundle args)
        {
            return new DRMContentAsyncTaskLoader(mContext, args);
        }

        @Override
        public void onLoadFinished(Loader<DRMContent> loader, DRMContent drmContent)
        {
            mDRMContentLoaderListener.onDRMContentInstanceCreated(drmContent);
        }

        @Override
        public void onLoaderReset(Loader<DRMContent> loader)
        {
        }

    }

}
