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

import java.io.*;
import java.net.*;
import java.util.*;

import android.content.Context;
import android.util.Log;
import com.insidesecure.drm.android.reference.LicenseAcquisitionHelper;
import com.insidesecure.drmagent.*;
import com.insidesecure.drmagent.entitlements.*;

/** Entitlement delegate which performs simple URL rewrites on the required URLs being passed as part of entitlement operations.
 * <br/><br/>
 * This class is only used to allow for more elaborate testing in the reference application and does not reflect real life usage
 *
 */
public class URLRewritingPlayReadyEntitlementDelegate extends SamplePlayReadyEntitlementDelegate
{
    private String TAG = URLRewritingPlayReadyEntitlementDelegate.class.getSimpleName();
    private final Context mContext;
    private final String mLicenseURLOverride;

    public URLRewritingPlayReadyEntitlementDelegate(Context context, final URL licenseURLOverride)
    {
        mContext = context;
        mLicenseURLOverride = licenseURLOverride != null ? licenseURLOverride.toString() : null;
    }

    @Override
    public DRMError acquireLicense(final DRMContent drmContent, final EntitlementRequest entitlementRequest, final EntitlementResponse entitlementResponse)
    {
        final String url = rewriteURL(entitlementRequest);
        final EntitlementRequest rewrittenURLEntitlementRequest = new EntitlementRequest(url,entitlementRequest.getEntitlementRequestData());
        return super.acquireLicense(drmContent, rewrittenURLEntitlementRequest, entitlementResponse);
    }

    private String rewriteURL(final EntitlementRequest entitlementRequest)
    {
        Log.d(TAG,"URL rewriting");
        Log.d(TAG,"  From: " + entitlementRequest.getServerURL());

        final String url = mLicenseURLOverride != null ? mLicenseURLOverride : LicenseAcquisitionHelper.performURLRewrite(mContext, entitlementRequest.getServerURL());

        Log.d(TAG,"  To: " + url);

        return url;
    }

    @Override
    public DRMError acknowledgeLicense(final DRMContent drmContent, final EntitlementRequest entitlementRequest, final EntitlementResponse entitlementResponse)
    {
        final String url = rewriteURL(entitlementRequest);
        final EntitlementRequest rewrittenURLEntitlementRequest = new EntitlementRequest(url,entitlementRequest.getEntitlementRequestData());
        return super.acknowledgeLicense(drmContent, rewrittenURLEntitlementRequest, entitlementResponse);
    }
}
