package io.trustbuilder.mfa.android.demoapp.screen;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import io.trustbuilder.mfa.android.demoapp.R;
import io.trustbuilder.mfa.android.demoapp.utils.CredentialProviderHandler;
import io.trustbuilder.mfa.lib.definition.AuthScope;
import io.trustbuilder.mfa.lib.usecase.IUseCase;
import io.trustbuilder.mfa.lib.usecase.definition.CredValue;
import io.trustbuilder.mfa.lib.usecase.definition.CredentialProvider;
import io.trustbuilder.mfa.lib.usecase.definition.authentication.Authentication;
import io.trustbuilder.mfa.lib.usecase.definition.authentication.AuthenticationParams;
import io.trustbuilder.mfa.lib.usecase.definition.authentication.AuthenticationSetupResult;

public class AuthenticationActivity extends TrustBuilderAuthenticationActivity {

    private EditText sessionId;
    private EditText cnxAlias;
    private String scope = "AUTH";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: AuthenticationUseCase");
        setTitle(this.getClass().getSimpleName());
        setContentView(R.layout.activity_authenticate);
        this.proceed = this.findViewById(R.id.proceed_Authenticate);
        this.tknAlias = this.findViewById(R.id.tknAlias_Authenticate);
        this.cnxAlias = this.findViewById(R.id.cnxAlias_Authenticate);
        this.result = this.findViewById(R.id.result_Authenticate);
        this.sessionId = this.findViewById(R.id.sessionId_Authenticate);
        Bundle b = getIntent().getExtras();
        if(b != null) {
            this.tknAlias.setText(b.getString("tknAlias"));
            this.sessionId.setText(b.getString("authSessionId"));
            this.cnxAlias.setText(b.getString("cnxAlias"));
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart: AuthenticationUseCase");
        this.proceed.setOnClickListener((v) -> {
                if (checkMandatoryField(tknAlias, "tknAlias")) return;
                if (checkMandatoryField(cnxAlias, "cnxAlias")) return;
                if (checkMandatoryField(sessionId, "sessionId")) return;
                AuthenticationParams request = new AuthenticationParams(tknAlias.getText().toString(), sessionId.getText().toString(), cnxAlias.getText().toString(), AuthScope.AUTH);
                try {
                    Authentication authentication = mfaLib.startAuthentication(request);
                    AuthenticationSetupResult setupResult = authentication.setup();
                    if (setupResult.isError()) {
                        displayJsonResult(setupResult.getError());
                    } else {
                        CredentialProviderHandler credentialProviderHandler = new CredentialProviderHandler();
                        CredentialProvider credentialProvider = credentialProviderHandler.resolveCredentialProviderFromList(setupResult.getResponse());
                        displayCredentials(credentialProvider.getCredType(), credentialProvider.getCredMode(), credentialProvider.getCredProperties().getBioChallenge(), authentication);
                    }
                } catch (Exception e) {
                    displayException(e);
                }
        });
    }

    @Override
    protected <T extends IUseCase> void executeUseCase(CredValue cred, T usecase) throws Exception {
        Object obj = usecase.execute(cred);
        displayJsonResult(obj);
    }

    protected void dropdownScopeSpinner(int id) {
        String[] items = new String[]{"AUTH", "SEAL", "SESSION"};
        Spinner dropdown = findViewById(id);
        List<String> itemsList = new ArrayList<>
                (Arrays.asList(items));
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, itemsList) {
            @Override
            public View getDropDownView(
                    int position, View convertView,
                    @NonNull ViewGroup parent) {
                View view = super.getDropDownView(
                        position, convertView, parent);
                TextView textView = (TextView) view;
                if (position == 0) {
                    textView.setTextColor(Color.GRAY);
                } else {
                    textView.setTextColor(Color.BLACK);
                }
                return view;
            }
        };
        adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        dropdown.setOnItemSelectedListener(
                new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(
                            AdapterView<?> parent, View view,
                            int position, long id) {
                        scope = (String) parent
                                .getItemAtPosition(position);
                    }

                    @Override
                    public void onNothingSelected(
                            AdapterView<?> parent) {
                        scope = "AUTH";
                    }
                });
        dropdown.setAdapter(adapter);
    }
}