//  TransactionInputsFragment.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.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.zeamster.paymentsdk.service.TransactionService;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;

public class TransactionInputsFragment extends Fragment implements View.OnClickListener {

    private LinearLayout parentLinearLayout;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_transaction_inputs, container, false);

        Button buttonSubmit = view.findViewById(R.id.btnSubmit);
        buttonSubmit.setOnClickListener(this);

        Button btnAdd = view.findViewById(R.id.btnAdd);
        btnAdd.setOnClickListener(this);

        String[] selections = getResources().getStringArray(R.array.selections);
        MainActivity.allSelections.clear();
        MainActivity.allSelections.addAll(Arrays.asList(selections));
        String[] items = new String[MainActivity.allSelections.size()];
        Spinner dropdown = view.findViewById(R.id.transactionParams);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item, MainActivity.allSelections.toArray(items));
        dropdown.setAdapter(adapter);

        MainActivity.selectedSelections = new LinkedList<>();
        parentLinearLayout = view.findViewById(R.id.parent);

        return view;
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btnAdd) {
            add(view);
        } else if (view.getId() == R.id.btnRemove) {
            remove(view);
        } else if (view.getId() == R.id.btnSubmit) {
            MainActivity.payload = getTransactionsInputMap();
            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            if (MainActivity.transactionCategory.equalsIgnoreCase("EMV")) {
                fragmentTransaction.replace(R.id.nav_host_fragment, new EMVTransactionFragment());
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
            } else {
                fragmentTransaction.replace(R.id.nav_host_fragment, new TransactionResponseFragment());
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
                processTransaction();
            }
            String[] selections = getResources().getStringArray(R.array.selections);
            MainActivity.allSelections.clear();
            MainActivity.allSelections.addAll(Arrays.asList(selections));
            String[] items = new String[MainActivity.allSelections.size()];
            ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item, MainActivity.allSelections.toArray(items));
            Spinner dropdown = view.getRootView().findViewById(R.id.transactionParams);
            dropdown.setAdapter(adapter);
        }
    }

    private void add(View view) {
        Spinner dropdown = view.getRootView().findViewById(R.id.transactionParams);
        String value = dropdown.getSelectedItem().toString();
        if (!value.isEmpty() && !value.equalsIgnoreCase("Please select a value..") && (MainActivity.selectedSelections.size() == 0 || !MainActivity.selectedSelections.contains(value))) {
            LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final View rowView = inflater.inflate(R.layout.transaction_input_row, null);
            final TextView label = rowView.findViewById(R.id.label);
            label.setText(value);
            MainActivity.selectedSelections.add(value);
            if (MainActivity.allSelections.contains(value)) {
                MainActivity.allSelections.remove(value);
                String[] items = new String[MainActivity.allSelections.size()];
                ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item, MainActivity.allSelections.toArray(items));
                dropdown.setAdapter(adapter);
            }
            parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount());
            Button btnRemove = rowView.findViewById(R.id.btnRemove);
            btnRemove.setOnClickListener(this);
        }
    }

    private void remove(View view) {
        View parent = (View) view.getParent().getParent();
        if (parent != null) {
            parent.setVisibility(View.GONE);
        }
        Spinner dropdown = view.getRootView().findViewById(R.id.transactionParams);
        TextView label = parent.findViewById(R.id.label);
        if (label != null && label.getText() != null && !label.getText().toString().isEmpty()
                && (MainActivity.selectedSelections.size() != 0 && MainActivity.selectedSelections.contains(label.getText()))) {
            String value = label.getText().toString();
            MainActivity.selectedSelections.remove(value);
            if (!MainActivity.allSelections.contains(value)) {
                MainActivity.allSelections.add(value);
                String[] items = new String[MainActivity.allSelections.size()];
                ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_dropdown_item, MainActivity.allSelections.toArray(items));
                dropdown.setAdapter(adapter);
            }
        }
    }

    private void processTransaction() {
        TransactionService transactionService = new TransactionService(MainActivity.restServiceClient);
        transactionService.processTransaction(MainActivity.transactionAction, MainActivity.payload, MainActivity.transactionId);
    }

    private HashMap<String, Object> getTransactionsInputMap() {
        HashMap<String, Object> payload = new HashMap<>();
        View parent = getView().findViewById(R.id.parent);
        if (parent != null && ((ViewGroup) parent).getChildCount() != 0) {
            int childCount = ((ViewGroup) parent).getChildCount();
            for (int i = 0; i < childCount; i++) {
                View child = ((ViewGroup) parent).getChildAt(i);
                View grandChild = ((ViewGroup) child).getChildAt(1);
                TextView textView = (TextView) ((ViewGroup) grandChild).getChildAt(0);
                grandChild = ((ViewGroup) child).getChildAt(2);
                EditText editText = (EditText) ((ViewGroup) grandChild).getChildAt(0);
                String label = textView.getText().toString();
                String userInput = editText.getText().toString();
                payload.put(label.replaceAll(" ", "_").toLowerCase(), userInput);
            }
        }
        return payload;
    }
}
