package com.beloko.quaketouch;

import android.content.Context;
import android.provider.Settings.Secure;
import android.util.Log;

import com.beloko.idtech.AppSettings;
import com.google.android.vending.licensing.AESObfuscator;
import com.google.android.vending.licensing.LicenseChecker;
import com.google.android.vending.licensing.LicenseCheckerCallback;
import com.google.android.vending.licensing.Policy;
import com.google.android.vending.licensing.ServerManagedPolicy;

public class License {

	private static final String LOG = "License";

	private static final int LIC_NETWORK_RETRIES = 5; //How many times to automatically retry license check
	private static final int LIC_MAX_UNLIC_CNT = 4; //Number of times it can run unlicened before quits 

	private static final String BASE64_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwV9m7sOybPyaeH2+2GX7lFx+66X7AN5TojJbCdT1E3c2fB9ujFcPYVVZBvHRjX0HMeJIodjfc4ydn1cWylMEnVM2TWFWzihZqXGctw9dx0JkHlhuZRDyVsJUij5DRAmcxcEhxMkJMYXTOHm09zGr8U2mzunT1NuKx1vK+Pi8MZab/PzCYvoVO3K8PF7kzZ7IrVh80IAhs7xhhvGb5UsQ/qgUFMn1suSTa4SbPNdrW9H2yLHCBoeIE1rAXzbalfE2/363Who3XH4wyJwrxpPtUSSkjiTLq9p6brZrXkw0CY7YmKfe0dsrOLCcB1KxnStK26tPHus3cmvPhWOEGrNwCQIDAQAB";

	// Generate your own 20 random bytes, and put them here.
	private static final byte[] SALT = new byte[] {
		-4, 12, 54, -12, -20, -57, -74, 99, 51, 19, 20, -45, 77, 17, -36, -33, 0, 6, 13,
		89
	};
	private LicenseCheckerCallback mLicenseCheckerCallback;
	private LicenseChecker mChecker;


	private int licNetworkRetries = LIC_NETWORK_RETRIES;

	Context ctx;
	
	public License(Context ctx)
	{
		this.ctx = ctx;
		String deviceId = Secure.getString(ctx.getContentResolver(), Secure.ANDROID_ID);

		mLicenseCheckerCallback = new MyLicenseCheckerCallback();
		// Construct the LicenseChecker with a policy.
		mChecker = new LicenseChecker(
				ctx, new ServerManagedPolicy(ctx,
						new AESObfuscator(SALT, ctx.getPackageName(), deviceId)),
						BASE64_PUBLIC_KEY);
	}

	private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
		public void allow(int  reason ) {

			if  (reason == Policy.LICENSED)
			{
				// Should allow user access.
				if (GD.DEBUG) Log.d(LOG,"LICENCE ALLOW  reason =" +  reason );
				AppSettings.setIntOption(ctx, "unlic_cnt", 0);
			}
			else
			{
				if (GD.DEBUG) Log.i(LOG,"License HACK detected");
				AppSettings.setIntOption(ctx, "unlic_cnt", LIC_MAX_UNLIC_CNT); //Force unlicensed
			}
		}

		public void dontAllow(int policyReason) {

			// displayResult(getString(R.string.dont_allow));
			// Should not allow access. In most cases, the app should assume
			// the user has access unless it encounters this. If it does,
			// the app should inform the user of their unlicensed ways
			// and then either shut down the app or limit the user to a
			// restricted set of features.
			// In this example, we show a dialog that takes the user to Market.
			// If the reason for the lack of license is that the service is
			// unavailable or there is another problem, we display a
			// retry button on the dialog and a different message.
			if (GD.DEBUG) Log.d(LOG,"LICENCE NOT ALLOWED! reason = " + policyReason);
			//displayDialog(policyReason == Policy.RETRY);
			if (policyReason == Policy.RETRY)
			{
				if (GD.DEBUG) Log.d(LOG,"License Can not contact server, tries left = " + licNetworkRetries);
				if (licNetworkRetries > 0)
				{
					licNetworkRetries--;
					mChecker.checkAccess(mLicenseCheckerCallback);
				}
				else
				{
					dontAllow(Policy.NOT_LICENSED);
				}
			}
			else // UNLICENSED
			{
				if (GD.DEBUG) Log.d(LOG,"UNLICENSED");
				
				//Increment number of times unlicensed
				int unliccnt = 	AppSettings.getIntOption(ctx, "unlic_cnt", 0);
				AppSettings.setIntOption(ctx, "unlic_cnt", unliccnt+1);
			}
		}
 
		public void applicationError(int errorCode) {

			Log.d(LOG,"LICENCE Error = " + errorCode);
		}
	}

	public void doCheck() {
		if (GD.DEBUG) Log.v(LOG, "doCheck()");
		licNetworkRetries = LIC_NETWORK_RETRIES;
		mChecker.checkAccess(mLicenseCheckerCallback);
	}


	public boolean isLicensed()
	{
		int unliccnt = 	AppSettings.getIntOption(ctx, "unlic_cnt", 0);
		if (unliccnt < LIC_MAX_UNLIC_CNT)
			return true;
		else
		{
			//Used all tries up
			return false;
		}	
	}

}
