package com.pasaoglu.mobilhanem.inappbilling;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.ConsumeResponseListener;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesUpdatedListener;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Optional;

public class MainActivity extends AppCompatActivity implements PurchasesUpdatedListener {

    private BillingClient mBillingClient;

    @BindView(R.id.btn_three_buy_health)
    Button btn_three_buy_health;

    @BindView(R.id.btn_ten_buy_health)
    Button btn_ten_buy_health;

    @BindView(R.id.btn_twenty_buy_health)
    Button btn_twenty_buy_health;

    @BindView(R.id.btn_fifty_buy_health)
    Button btn_fifty_buy_health;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        mBillingClient = BillingClient.newBuilder(this).setListener(this).build();
        mBillingClient.startConnection(new BillingClientStateListener() {
            @Override
            public void onBillingSetupFinished(@BillingClient.BillingResponse int billingResponseCode) {
                if (billingResponseCode == BillingClient.BillingResponse.OK) {
                    // The billing client is ready. You can query purchases here.
                    // BUTONLARI AKTIF ET
                    enableOrDisableButtons(true);

                } else {
                    //TODO Kullanıcıya uyarı ver
                    Toast.makeText(MainActivity.this, "Ödeme sistemi için google play hesabını kontrol ediniz", Toast.LENGTH_SHORT).show();
                    enableOrDisableButtons(false);
                }
            }

            @Override
            public void onBillingServiceDisconnected() {
                // Try to restart the connection on the next request to
                // Google Play by calling the startConnection() method.
                //TODO Kullanıcıya uyarı ver
                enableOrDisableButtons(false);
                Toast.makeText(MainActivity.this, "Ödeme sistemi şuanda geçerli değil", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void enableOrDisableButtons(boolean isEnabled) {
        btn_three_buy_health.setEnabled(isEnabled);
        btn_ten_buy_health.setEnabled(isEnabled);
        btn_twenty_buy_health.setEnabled(isEnabled);
        btn_fifty_buy_health.setEnabled(isEnabled);
    }
    @Optional
    @OnClick(R.id.btn_three_buy_health)
    void buyThreeHealth(View view) {
        buyProduct("3_buy_health");
    }
    @Optional
    @OnClick(R.id.btn_ten_buy_health)
    void buyTenHealth(View view) {
        buyProduct("10_buy_health");
    }
    @Optional
    @OnClick(R.id.btn_twenty_buy_health)
    void buyTwentyHealth(View view) {
        buyProduct("20_buy_health");
    }
    @Optional
    @OnClick(R.id.btn_fifty_buy_health)
    void buyFiftyHealth(View view) {
        buySubscription("50_buy_health");
    }

    private void buyProduct(String skuId) {
        BillingFlowParams flowParams = BillingFlowParams.newBuilder()
                .setSku(skuId)
                .setType(BillingClient.SkuType.INAPP)
                .build();
        mBillingClient.launchBillingFlow(this, flowParams);
    }

    private void buySubscription(String skuId) {
        BillingFlowParams flowParams = BillingFlowParams.newBuilder()
                .setSku(skuId)
                .setType(BillingClient.SkuType.SUBS)
                .build();
        mBillingClient.launchBillingFlow(this, flowParams);
    }


    @Override
    public void onPurchasesUpdated(int responseCode, @Nullable List<Purchase> purchases) {
        if (responseCode == BillingClient.BillingResponse.OK
                && purchases != null) {
            for (final Purchase purchase : purchases) {
                mBillingClient.consumeAsync(purchase.getPurchaseToken(), new ConsumeResponseListener() {
                    @Override
                    public void onConsumeResponse(int responseCode, String purchaseToken) {
                        if (responseCode == BillingClient.BillingResponse.OK) {
                            //sendTransactionData(purchase.getPurchaseToken(), purchase.getSku());
                        }
                    }
                });
            }
        } else if (responseCode == BillingClient.BillingResponse.USER_CANCELED) {
            // Handle an error caused by a user canceling the purchase flow.
            billingCanceled();

        } else {
            billingCanceled();
        }
    }

    private void billingCanceled() {

    }



}
