Vedroid36
3/26/2014 - 4:40 PM

Payment - dev branch (test OK)

package com.Klitch.Sprints.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.Klitch.Sprints.R;
import com.Klitch.Sprints.api.ApiRequestAsyncLoader;
import com.Klitch.Sprints.api.UpdateSubscriptionsDBTask;
import com.Klitch.Sprints.billing_utill.*;
import com.Klitch.Sprints.helpers.JsonStringRequest;
import com.Klitch.Sprints.helpers.Lo;
import com.Klitch.Sprints.helpers.Constants;
import com.Klitch.Sprints.helpers.Utils;
import com.Klitch.Sprints.holders.AllCommunitiesHolder;
import com.google.gson.Gson;


/**
 * Created by Aleks on 22.02.14.
 */
public class PaymentActivity extends ActionBarActivity implements View.OnClickListener, LoaderManager.LoaderCallbacks<String> {

    private static final int SUBSCRIPTION_PERIOD_1_MONTH = 1;
    private static final int SUBSCRIPTION_PERIOD_3_MONTHS = 3;
    private static final int SUBSCRIPTION_PERIOD_6_MONTHS = 6;
    private static final int SUBSCRIPTION_PERIOD_12_MONTHS = 12;

    private static final String PROCESSED_BY = "google play";
    private static final int LOADER_PUT_SUBSCRIPTIONS = 2;
    private static final int LOADER_JOIN_COMMUNITY = 3;

    private final String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAl84Rtefaw4JwvMTEehRcmPtepS6r9gHQa5o+XnuBIxH+1LobHc3iU1fk8aLXMDXzn+n3JX3oocegL04KL42rX8P4xBmTlUg5e7px1zutpvkxgrkwANf7ccjA3OHafxwMwAqDWpaqrrk5zTV6PUi/TasmIJXbUqS9pnV3INWjKEiIY+zNxnMSxpVWkY9k5Gb2OH9Lo6SOgszr+aeNO6MNnNuZci4yRwMou8mvZOm7Bkx8qyCDhKLQv4GLsr3tOs/XnlXhO/BjW8HkWAvN8NytNH/+1+lVIXkF7ZzMuqvjXfV0lpxnhPbsxVAlRxMDKTh54Jm6I5RO3NlZgWPuhJ4byQIDAQAB";
    static final String ITEM_SKU = "android.test.purchased";

    private String FAKE_ITEM_SKU;
    private int selectedPeriod;

    private Lo lo= new Lo(PaymentActivity.this);

    private RadioGroup radioGroupPeriod;
    private Button buttonCancel,buttonJoin;
    private ProgressBar progress_bar;

    private IabHelper billingHelper;
    private ApiRequestAsyncLoader loader;
    private String communityID;
    private AllCommunitiesHolder com_data;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        lo.g("onCreate");
        setContentView(R.layout.activity_payment);
        createActionBar();

        if (getIntent() != null) {
            Integer id = getIntent().getIntExtra("com_id", -1);
            communityID = id.toString();
             //getStringExtra("com_id");
        }

        lo.g("communityID:  " + communityID);


        buttonCancel = (Button)findViewById(R.id.buttonCancel);
        buttonJoin = (Button)findViewById(R.id.buttonJoin);
        radioGroupPeriod = (RadioGroup)findViewById(R.id.radioGroupSubscPeriod);

        buttonCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onButtonCancelClick();
            }
        });
        buttonJoin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onButtonJoinClick();
            }
        });
        radioGroupPeriod.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                onRadioButtonChecked(i);
            }
        });

        // init in-app Billin Helper
        billingHelper = new IabHelper(this, base64EncodedPublicKey);
        billingHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
            public void onIabSetupFinished(IabResult result) {
                if ( !result.isSuccess() ) {
                    lo.g("In-app Billing setup failed: " + result);
                } else {
                    lo.g("In-app Billing is set up OK");
                }
            }
        });
        //Security.verify(base64EncodedPublicKey, );
    }

    private void createActionBar() {
        ActionBar mActionBar = getSupportActionBar();
        mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        View actBarView = getLayoutInflater().inflate(R.layout.cust_act_bar_backbtn, null);
        ((TextView) actBarView.findViewById(R.id.title)).setText(getResources().getString(R.string.act_bar_payment_title));
        actBarView.findViewById(R.id.leftImg).setOnClickListener(this);
        mActionBar.setCustomView(actBarView);
        progress_bar = (ProgressBar) actBarView.findViewById(R.id.progress_bar);
    }

    private void onButtonCancelClick(){
        finish();
    }

    private void onButtonJoinClick(){
        // if (billingHelper != null) billingHelper.flagEndAsync();
        billingHelper.launchPurchaseFlow(this, ITEM_SKU, 10001, mPurchaseFinishedListener, "mypurchasetoken");
    }

    private void onRadioButtonChecked(int i){
        lo.g("onRadioButtonChecked");

        // ToDO: for production replace test purchase items with real

        switch (radioGroupPeriod.getCheckedRadioButtonId()) {
            case R.id.radio_month_1:
                FAKE_ITEM_SKU = Constants.TEST_SUBSCRIBTION_SKU_1_MONTH;
                selectedPeriod = SUBSCRIPTION_PERIOD_1_MONTH;
                break;
            case R.id.radio_month_3:
                FAKE_ITEM_SKU = Constants.TEST_SUBSCRIBTION_SKU_3_MONTHS;
                selectedPeriod = SUBSCRIPTION_PERIOD_3_MONTHS;
                break;
            case R.id.radio_month_6:
                FAKE_ITEM_SKU = Constants.TEST_SUBSCRIBTION_SKU_6_MONTHS;
                selectedPeriod = SUBSCRIPTION_PERIOD_6_MONTHS;
                break;
            case R.id.radio_month_12:
                FAKE_ITEM_SKU = Constants.TEST_SUBSCRIBTION_SKU_12_MONTHS;
                selectedPeriod = SUBSCRIPTION_PERIOD_12_MONTHS;
                break;
        }
        lo.g("FAKE_ITEM_SKU:  " + FAKE_ITEM_SKU);
        lo.g("ITEM_SKU:  " + ITEM_SKU);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.leftImg:
                finish();
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        lo.g("onActivityResult(" + requestCode + "," + resultCode + "," + data + " )");

        if ( billingHelper.handleActivityResult(requestCode, resultCode, data) == false ) {
            super.onActivityResult(requestCode, resultCode, data);
        } else {
            lo.g("onActivityResult handled by IABUtil.");
        }
    }

    IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
        public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
            lo.g("onIabPurchaseFinished:  result" + result.getMessage());
            lo.g("purchase: " + purchase);

            if (result.isFailure()) {
                lo.g("isFailure ");
                return;
            } else if (purchase.getSku().equals(ITEM_SKU)) {
                lo.g("purchase.getSku().equals(ITEM_SKU) ");
                consumeItem();
                lo.g("purchase.getSku(): " + purchase.getSku());
            }
        }
    };

    public void consumeItem() {
        if (billingHelper != null) billingHelper.flagEndAsync();
        billingHelper.queryInventoryAsync(mReceivedInventoryListener);
    }

    IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
        public void onQueryInventoryFinished(IabResult result,   Inventory inventory) {

            if (result.isFailure()) {
                lo.g("onQueryInventoryFinished is failed");
            } else {
                billingHelper.consumeAsync(inventory.getPurchase(ITEM_SKU), mConsumeFinishedListener);
            }
            if (inventory.hasPurchase(ITEM_SKU)) {
                if (billingHelper != null) billingHelper.flagEndAsync();
                billingHelper.consumeAsync(inventory.getPurchase(ITEM_SKU), null);
            }
        }
    };

    IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
        public void onConsumeFinished(Purchase purchase, IabResult result) {
            lo.g("onConsumeFinished,  purchase:  " + purchase.getSku() + ",  result " + result);

            if (result.isSuccess() == true) {
                handleSuccessConsume();
                  } else {
                lo.g("onConsumeFinished is failed");
            }
        }

    };

    private void handleSuccessConsume(){

        UpdateSubscriptionsDBTask updateDBtask = new UpdateSubscriptionsDBTask();
        updateDBtask.execute(selectedPeriod);

        if (getSupportLoaderManager().getLoader(LOADER_PUT_SUBSCRIPTIONS) == null) {
            getSupportLoaderManager().initLoader(LOADER_PUT_SUBSCRIPTIONS, null, this).forceLoad();
        } else {
            getSupportLoaderManager().restartLoader(LOADER_PUT_SUBSCRIPTIONS, null, this).forceLoad();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (billingHelper != null) billingHelper.dispose();
        billingHelper = null;
    }

    @Override
    public Loader<String> onCreateLoader(int loaderID, Bundle bundle) {
        lo.g("onCreateLoader,  loaderID: " + loaderID);

        progress_bar.setVisibility(View.VISIBLE);

        if (LOADER_PUT_SUBSCRIPTIONS == loaderID) {
            JsonStringRequest request = new JsonStringRequest();
            request.add("sku", FAKE_ITEM_SKU);
            request.add("processed_by", PROCESSED_BY);
            String json_request = request.getStringJson();
            lo.g("json_request: " + json_request);
            loader = new ApiRequestAsyncLoader(this, "current/subscriptions", json_request, "put");
        } else if (LOADER_JOIN_COMMUNITY == loaderID) {
            lo.g("communityID: " + communityID);
            String json_request = "{\"id\": " + communityID + "}";
            loader = new ApiRequestAsyncLoader(this, "current/memberships", json_request, "put");
        }

        return loader;
    }

    @Override
    public void onLoadFinished(Loader<String> objectLoader, String response) {
        lo.g("onLoadFinished, Loader ID:  " + objectLoader.getId());

        if (Utils.checkResponse(this, response) == false) {
            return;
        }

        if (LOADER_PUT_SUBSCRIPTIONS == objectLoader.getId()) {
            lo.g("response:  " + response);

            getSupportLoaderManager().restartLoader(LOADER_JOIN_COMMUNITY, null, this).forceLoad();

        } else if (LOADER_JOIN_COMMUNITY == objectLoader.getId()){
            Intent menu_intent = new Intent(this, MenuActivity.class);
            menu_intent.putExtra("fragment", "MyCommunityFragment");
            startActivity(menu_intent);
            Toast.makeText(this, "Вы вступили в сообщество", Toast.LENGTH_SHORT).show();
            finish();
        }
        progress_bar.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onLoaderReset(Loader<String> objectLoader) {

    }

}