package demo.mapi.ccv.eu.mapi_demo.activities.unattended;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.Gson;
import demo.mapi.ccv.eu.mapi_demo.AndroidLogger;
import demo.mapi.ccv.eu.mapi_demo.MapiDemoState;
import demo.mapi.ccv.eu.mapi_demo.R;
import eu.ccvlab.mapi.core.logging.MPALogging;
import org.apache.commons.lang.StringUtils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class UnAttendedSettingsActivity extends AppCompatActivity {
    EditText terminalIp;
    EditText amount;
    EditText minimumAmount;
    EditText totalAmount;
    Button sdkButton;
    Button apiButton;

    private MapiDemoState appState = new MapiDemoState();
    private boolean useRestApi;

    @SuppressWarnings("PMD.AvoidPrintStackTrace")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.unattended_settings_activity);
        terminalIp = findViewById(R.id.unattended_terminal_ip);
        amount = findViewById(R.id.unattended_amount);
        minimumAmount = findViewById(R.id.unattended_minimum_amount);
        totalAmount = findViewById(R.id.unattended_total_amount);
        sdkButton = findViewById(R.id.sdk_button);
        apiButton = findViewById(R.id.api_button);
        findViewById(R.id.terminal_save_button).setOnClickListener((View view) -> onClickSave());
        findViewById(R.id.api_button).setOnClickListener((View view) -> onClickApiButton());
        findViewById(R.id.sdk_button).setOnClickListener((View view) -> onClickSdkButton());
        MPALogging.addLogger(new AndroidLogger("UnAttendedSettingsActivity"));
        loadLastAppState();
    }

    @Override
    protected void onStart() {
        super.onStart();
        refreshDisplayedSettings();
    }

    public void onClickSave() {
        if (StringUtils.isNotEmpty(amount.getText().toString()) && StringUtils.isNotEmpty(terminalIp.getText().toString()) && StringUtils.isNotEmpty(minimumAmount.getText().toString()) && StringUtils.isNotEmpty(totalAmount.getText().toString())) {
            saveNewAppState();
            onBackPressed();
        } else {
            Toast.makeText(this, "Please fill in all fields", Toast.LENGTH_LONG).show();
        }
    }

    public void onClickApiButton() {
        useRestApi = true;
        useApi();
    }

    public void onClickSdkButton() {
        useRestApi = false;
        useSdk();
    }

    @SuppressLint("LongLogTag")
    private void loadLastAppState() {
        String xml = null;
        try {
            File file = getApplicationContext().getFileStreamPath("state.json");

            int size = (int) file.length();
            byte[] bytes = new byte[size];
            BufferedInputStream buf;

            buf = new BufferedInputStream(new FileInputStream(file));
            buf.read(bytes, 0, bytes.length);
            buf.close();

            xml = new String(bytes);
        } catch (IOException e) {
            Log.e("AttendedTerminalActivity", "Unable to read previous app state");
        }

        this.appState = xml != null ? new Gson().fromJson(xml, MapiDemoState.class) : new MapiDemoState();
    }

    @SuppressLint("LongLogTag")
    private void saveNewAppState() {
        try {
            String protocol = "OPI-NL";
            appState.setUnAttendedHostname(protocol, terminalIp.getText().toString());
            appState.setUnAttendedAmount(protocol, amount.getText().toString());
            appState.setUnAttendedMinimumAmount(protocol, minimumAmount.getText().toString());
            appState.setUnAttendedTotalAmount(protocol, totalAmount.getText().toString());
            appState.setRestApi(protocol, useRestApi);
            Gson gson = new Gson();
            String json = gson.toJson(this.appState);
            FileOutputStream fileOutputStream = getApplicationContext().openFileOutput("state.json", Context.MODE_PRIVATE);
            fileOutputStream.write(json.getBytes());
            fileOutputStream.close();
        } catch (IOException e) {
            Log.e("UnAttendedSettingsActivity", "Failed to save app state: " + e.getLocalizedMessage());
        }
    }

    private void refreshDisplayedSettings() {
        String protocol = "OPI-NL";
        terminalIp.setText(appState.getUnAttendedHostname(protocol));
        amount.setText(appState.getUnAttendedAmount(protocol));
        minimumAmount.setText(appState.getUnAttendedMinimumAmount(protocol));
        totalAmount.setText(appState.getUnAttendedTotalAmount(protocol));
        useRestApi = appState.getRestApi(protocol);
        if (useRestApi) {
            useApi();
        } else {
            useSdk();
        }
    }

    private void useApi() {
        setButtonActive(apiButton);
        setButtonInactive(sdkButton);
    }

    private void useSdk() {
        setButtonActive(sdkButton);
        setButtonInactive(apiButton);
    }


    private void setButtonActive(Button button) {
        button.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        button.setTextColor(getResources().getColor(R.color.white));
    }

    private void setButtonInactive(Button button) {
        button.setBackgroundColor(getResources().getColor(R.color.white));
        button.setTextColor(getResources().getColor(R.color.black));
    }
}
