//  TransactionResponseFragment.java
//  Sample App for PaymentSDK
//
//  Created by Samstaurej Siddiquie on 01/10/2019.
//  Copyright © 2019 Zeamster. All rights reserved.

package com.zeamster.sampleapp;

import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import org.json.JSONException;
import org.json.JSONObject;

import pl.droidsonroids.gif.GifImageView;

public class TransactionResponseFragment extends Fragment {

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        final View root = inflater.inflate(R.layout.transaction_response_fragment, container, false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                checkAndShowResponse(root);
            }
        }, 5000);
        return root;
    }

    private void checkAndShowResponse(final View view) {
        TextView outputJASON = view.findViewById(R.id.txtResultJSON);
        if (MainActivity.apiResponse != null && !MainActivity.apiResponse.isEmpty()) {
            try {
                JSONObject jsonObject = new JSONObject(MainActivity.apiResponse);
                outputJASON.setText(jsonObject.toString(2));
            } catch (JSONException e) {
                outputJASON.setText(e.getMessage());
            }
            GifImageView loader = view.findViewById(R.id.loader);
            loader.setVisibility(View.GONE);
            outputJASON.setVisibility(View.VISIBLE);
            if (!MainActivity.apiResponse.contains("error") && MainActivity.apiResponse.contains("transaction")) {
                AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
                alert.setPositiveButton("Ok", null);
                alert.setTitle("Success!");
                alert.setMessage("Transaction has been performed Successfully");
                alert.show();
            }
        } else {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    checkAndShowResponse(view);
                }
            }, 3000);
        }
    }
}
