package com.programmer.example.pardakht;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.programmer.example.pardakht.util.IabHelper;
import com.programmer.example.pardakht.util.IabResult;
import com.programmer.example.pardakht.util.Inventory;
import com.programmer.example.pardakht.util.Purchase;

import java.util.Calendar;
import java.util.Date;

public class pardakh_bazaar extends AppCompatActivity {


    static final String TAG = "aaaaa";

    // SKUs for our products: the premium upgrade (non-consumable)

    static final String SKU_PREMIUM = "zamany_kala";

    // Does the user have the premium upgrade?
    boolean mIsPremium = true;

    // (arbitrary) request code for the purchase flow
    static final int RC_REQUEST = 1367;

    // The helper object
    IabHelper mHelper;
    IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener;
    IabHelper.QueryInventoryFinishedListener mGotInventoryListener;

    ProgressDialog nDialog;
    boolean javab_server = false;
    boolean bo = false;

    TextView txt;

    SharedPreferences.Editor edits_s;
    SharedPreferences prefs_s;
    String msg_s;


    // start mahdodiat
    SharedPreferences.Editor edits_Tahlil;
    SharedPreferences tahlil;
    int int_tahlil;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pardakh_bazaar);


         txt = (TextView) findViewById(R.id.textView);


        //*****

        try {

            tahlil = getSharedPreferences("tahlil", MODE_PRIVATE);
            int_tahlil = tahlil.getInt("tahlil",0);

            Log.d(TAG, "onCreate: int_tahlil = "+ int_tahlil);

            if (int_tahlil == 0){
                txt.setText("هیچ اعتباری خریداری نشده است.");

            }else if (int_tahlil == 1){

                prefs_s = getSharedPreferences("prefs_s", MODE_PRIVATE);
                final String msg_s = prefs_s.getString("prefs_s","");

                txt.setText("برنامه اموزشی تا تاریخ "+msg_s+" فعال میباشد.");

            }else if (int_tahlil == 2){

                prefs_s = getSharedPreferences("prefs_s", MODE_PRIVATE);
                String msg_s = prefs_s.getString("prefs_s","");

                txt.setText("اعتبار خریداری شده در تاریخ "+msg_s+" خاتمه یافته است لطفا اعتبار جدید خریداری کنید.");

            }

        }catch (Exception e){
            txt.setText("هیچ اعتباری خریداری نشده است.");
            Log.d(TAG, "onCreate: int_tahlil = Erorr");

        }

        //*****    *****//

        String base64EncodedPublicKey = "MIHNMA0GCSqGSIb3DQEBAQUAA4G7ADCBtwKBrwC6mLlUM4KrAj6leS11K/peN1JDaKsP2rTmdueoN4tvN0gSgcvQ74W9ipOxYTgLAoAElZ3uRV2n4DroexdMTxhdrhmzdNMms5NnLWme/vO+P+p5fUbr8BNgSesjz/wfPONLasR71+AlgIIePCTxZ+qwC7nXYXhmcQ+x5zAApReEdZNLZxFWVA5J0Pp5w1ZBfDdzrgWnx63VUv3v/q8p+getw4X+XXX5p6bbIxt//5kCAwEAAQ==";


        mHelper = new IabHelper(this, base64EncodedPublicKey);



        mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
            public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
                Log.d(TAG, "Query inventory finished.");

                javab_server = true;

                if (result.isFailure()) {
                    Log.d(TAG, "Failed to query inventory: " + result);
                    return;
                } else {
                    Log.d(TAG, "Query inventory was successful.");
                    // does the user have the premium upgrade?
                    mIsPremium = inventory.hasPurchase(SKU_PREMIUM);
                    if (mIsPremium) {
                        MasrafSeke(inventory.getPurchase(SKU_PREMIUM));
                    }
                    // update UI accordingly

                    Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
                }

                Log.d(TAG, "Initial inventory query finished; enabling main UI.");



            }


        };








        mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
            public void onIabPurchaseFinished(IabResult result, Purchase purchase) {

                if (result.isFailure()) {
                    Log.d(TAG, "Error purchasing: " + result);
                    return;
                } else if (purchase.getSku().equals(SKU_PREMIUM)) {
                    // give user access to premium content and update the UI
                    Toast.makeText(pardakh_bazaar.this, "خرید با موفقیت انجام شد", Toast.LENGTH_SHORT).show();

                    long timestampString = purchase.getPurchaseTime();

                    Date date = new Date(Long.parseLong(String.valueOf(timestampString)));

                    Log.d(TAG, "MasrafSeke(purchase) purchase.getPurchaseTime() = "+ date );

                    getTarikh(date);
                    MasrafSeke(purchase);

                }

            }



        };






        Log.d(TAG, "Starting setup.");

        mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
            public void onIabSetupFinished(IabResult result) {
                Log.d(TAG, "Setup finished.");

                if (!result.isSuccess()) {
                    // Oh noes, there was a problem.
                    Log.d(TAG, "Problem setting up In-app Billing: " + result);
                }else {
                    Log.d(TAG, "Starting setup.");
                }
                // Hooray, IAB is fully set up!
                mHelper.queryInventoryAsync(mGotInventoryListener);
            }
        });

    }




    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data);

        // Pass on the activity result to the helper for handling
        if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
            super.onActivityResult(requestCode, resultCode, data);
        } else {
            Log.d(TAG, "onActivityResult handled by IABUtil.");
        }
    }


    @Override
    public void onDestroy() {
        //از سرویس در زمان اتمام عمر activity قطع شوید
        super.onDestroy();
        if (mHelper != null) mHelper.dispose();
        mHelper = null;
    }



    private void MasrafSeke(Purchase kala) {
        // برای اینکه کاربر فقط یکبار بتواند از کالای فروشی استفاده کند
        // باید بعد از خرید آن کالا را مصرف کنیم
        // در غیر اینصورت کاربر با یکبار خرید محصول می تواند چندبار از آن استفاده کند
        mHelper.consumeAsync(kala, new IabHelper.OnConsumeFinishedListener() {
            @Override
            public void onConsumeFinished(Purchase purchase, IabResult result) {
                if (result.isSuccess())
                    Toast.makeText(pardakh_bazaar.this, "مصرف شد", Toast.LENGTH_SHORT).show();
                Log.d(TAG, "NATIJE masraf: " + result.getMessage() + result.getResponse());

            }
        });
    }

    public void onClick(View view) {
        Log.d(TAG, "onClick : ");

        if ( bo == false){
            nDialog = new ProgressDialog(pardakh_bazaar.this);
            nDialog.setTitle("بررسی اینترنت");
            nDialog.setMessage("در حال بارگزاری ..");
            nDialog.setIndeterminate(false);
            nDialog.setCancelable(true);
            nDialog.show();

            onClikkkkkk();
        }else {
            Intent n = new Intent(getApplicationContext(),MainActivity.class);
            startActivity(n);
        }

    }

    private void onClikkkkkk() {

        if (javab_server == true) {

            nDialog.dismiss();

            mHelper.launchPurchaseFlow(this, SKU_PREMIUM, RC_REQUEST, mPurchaseFinishedListener, "payload-string");

            javab_server = false;
            bo = true;
        }

        new CountDownTimer(5000,1000){
            @Override
            public void onTick(long millisUntilFinished){}

            @Override
            public void onFinish(){
                // your code

                onClikkkkkk();
            }
        }.start();






    }



    private void getTarikh(Date dateee) {

        String f = String.valueOf(dateee);
        String ff[] = f.split(" ");

        int day_kharid = Integer.parseInt(ff[2]);
        String month_kharid = ff[1];
        int year_kharid = Integer.parseInt(ff[5]);
        int mm =0;


        if (month_kharid.contains("Jan")){
            mm = 1;
        }else if (month_kharid.contains("Feb")){
            mm = 2;
        }else if (month_kharid.contains("Mar")){
            mm = 3;
        }else if (month_kharid.contains("Apr")){
            mm = 4;
        }else if (month_kharid.contains("May")){
            mm = 5;
        }else if (month_kharid.contains("Jun")){
            mm = 6;
        }else if (month_kharid.contains("Jul")){
            mm = 7;
        }else if (month_kharid.contains("Aug")){
            mm = 8;
        }else if (month_kharid.contains("Sep")){
            mm = 9;
        }else if (month_kharid.contains("Oct")){
            mm = 10;
        }else if (month_kharid.contains("Nov")){
            mm = 11;
        }else if (month_kharid.contains("Dec")){
            mm = 12;
        }



        JalaliCalendar.gDate miladyDate_kh = new JalaliCalendar.gDate(year_kharid,mm,day_kharid);
        JalaliCalendar.gDate jalalyDate_kh = JalaliCalendar.MiladiToJalali(miladyDate_kh);



        int sal_kh = jalalyDate_kh.getYear();
        int month_kh = jalalyDate_kh.getMonth();
        int day_kh = jalalyDate_kh.getDay();


        String str_kh = sal_kh+"/"+month_kh+"/"+day_kh;


        Log.d(TAG, "getTarikh: kharid = "+sal_kh+"/"+month_kh+"/"+day_kh);


        // for khaid sal
        String sal_nahay = (sal_kh+1)+"/"+month_kh+"/"+day_kh;
        Log.d(TAG, "getTarikh: kharid_until year = " + sal_nahay);

        txt.setText(sal_nahay);


        prefs_s = getSharedPreferences("prefs_s", MODE_PRIVATE);
        edits_s = prefs_s.edit();
        String input = sal_nahay;
        edits_s.putString("prefs_s", String.valueOf(input));
        edits_s.commit();


//===========================
//===========================





        // Tarikh shamsy emrooz
        Calendar cal = Calendar.getInstance();
        int year1 = cal.get(Calendar.YEAR);
        int month1 = cal.get(Calendar.MONTH);
        int day1 = cal.get(Calendar.DAY_OF_MONTH);




        int s_day = cal.get(Calendar.DAY_OF_WEEK);
        String ssd ="";

        if (s_day==1){
            ssd = "یکشنبه";
        }else if (s_day==2){
            ssd = "دوشنبه";

        }else if (s_day==3){
            ssd = "سه شنبه";
        }else if (s_day==4){
            ssd = "چهار شنبه";
        }else if (s_day==5){
            ssd = "پنج شنبه";
        }else if (s_day==6){
            ssd = "جمعه";
        }else if (s_day==7){
            ssd = "شنبه";
        }




        String date = year1+"/"+month1+"/"+day1;


        JalaliCalendar.gDate miladyDate = new JalaliCalendar.gDate(year1,month1,day1);
        JalaliCalendar.gDate jalalyDate = JalaliCalendar.MiladiToJalali(miladyDate);
        String a = jalalyDate.toString();



        String saly = String.valueOf(jalalyDate.getYear());
        int month = jalalyDate.getMonth()+1;
        int day = jalalyDate.getDay();


        String emrooz = saly+"/"+month+"/"+day;

        Log.d("aaaaa", "getTarikh: mobile = "+emrooz);

        Sanjesh_Tarikh(emrooz,sal_nahay);


    }




    private void Sanjesh_Tarikh(String emrooz, String sal_nahay) {

 //       1397/5/7
//*****
        String em_em[] = emrooz.split("/");

        int sal   = Integer.parseInt(em_em[0]);
        int month = Integer.parseInt(em_em[1]);
        int day   = Integer.parseInt(em_em[2]);

//*****   *****//

        if (sal_nahay.length() > 5){
            String sa_sa[] = sal_nahay.split("/");
            int sa_sal = Integer.parseInt(sa_sa[0]);
            int sa_mon = Integer.parseInt(sa_sa[1]);
            int sa_day = Integer.parseInt(sa_sa[2]);

            if (sa_sal == sal && sa_mon == month && sa_day < day){
                txt.setText("اعتبار خریداری شده در تاریخ "+sal_nahay+" خاتمه یافته است لطفا اعتبار جدید خریداری کنید.");

                tahlil = getSharedPreferences("tahlil", MODE_PRIVATE);
                edits_Tahlil = tahlil.edit();
                int input_Tahlil = 2;
                edits_Tahlil.putInt("tahlil", input_Tahlil);
                edits_Tahlil.commit();

            }else {
                txt.setText("برنامه اموزشی تا تاریخ "+sal_nahay+" فعال میباشد.");

                tahlil = getSharedPreferences("tahlil", MODE_PRIVATE);
                edits_Tahlil = tahlil.edit();
                int input_Tahlil = 1;
                edits_Tahlil.putInt("tahlil", input_Tahlil);
                edits_Tahlil.commit();
            }


        }else {
            txt.setText("هیچ اعتباری خریداری نشده است.");

            tahlil = getSharedPreferences("tahlil", MODE_PRIVATE);
            edits_Tahlil = tahlil.edit();
            int input_Tahlil = 0;
            edits_Tahlil.putInt("tahlil", input_Tahlil);
            edits_Tahlil.commit();
        }





    }



}
