package com.example.onetap_ssh.ui.terminal;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Vibrator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

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

import java.util.Objects;

import com.example.onetap_ssh.MainActivity;
import com.example.onetap_ssh.R;

public class TerminalFragment extends Fragment {

    public static boolean atBottom = false;

    public static String command;

    Button send_button;
    EditText terminal_edit_text;
    TextView terminal_textView;
    Terminal terminal;
    ScrollView scrollView;
    public static String user, password, ip;



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

        View root = inflater.inflate(R.layout.fragment_terminal, container, false);
        SharedPreferences prefs = requireContext().getSharedPreferences("appsettings", Context.MODE_PRIVATE);
        user = prefs.getString("user", null);
        password = prefs.getString("password", null);
        ip = prefs.getString("ip", null);
        if (user == null || ip == null || password == null) {
            AlertDialog mDialog = new AlertDialog.Builder(getContext())
                    .setTitle(getString(R.string.unable_to_connect))
                    .setMessage(getString(R.string.please_login))

                    // Specifying a listener allows you to take an action before dismissing the dialog.
                    // The dialog is automatically dismissed when a dialog button is clicked.
                    .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (MainActivity.button_vibration) {
                                Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                                assert vr != null;
                                vr.vibrate(100);
                            }
                        }
                    }).create();
            Objects.requireNonNull(mDialog.getWindow()).setBackgroundDrawableResource(R.drawable.button_round);
            mDialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //style id
            mDialog.show();

        } else {
            scrollView = (ScrollView) root.findViewById((R.id.scrollView));
            terminal_edit_text = (EditText) root.findViewById(R.id.terminal_edit_text);
            send_button = (Button) root.findViewById(R.id.send_button);
            send_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (MainActivity.button_vibration) {
                        Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                        assert vr != null;
                        vr.vibrate(100);
                    }
                    if (terminal != null) {
                        terminal.sendTerminalCommand(terminal_edit_text.getText().toString());
                        if (atBottom) {
                            final Handler handler = new Handler(Looper.getMainLooper());
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    scrollView.fullScroll(View.FOCUS_DOWN);
                                }

                            }, 500);
                        }}

                }

            });

            terminal_textView = (TextView) root.findViewById(R.id.terminal_textView);
            new Thread() {
                public void run() {
                    try {
                        terminal = new Terminal();
                    } catch (Exception e) {
                        requireActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getContext(), R.string.unable_to_connect, Toast.LENGTH_SHORT).show();

                            }
                        });
                        return;
                    }

                    requireActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getContext(), R.string.connected, Toast.LENGTH_SHORT).show();
                        }
                    });
                    while (terminal != null) {

                        if (getActivity() == null) {

                            return;
                        }

                        try {
                            requireActivity().runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    atBottom = scrollView.getChildAt(0).getBottom() <= (scrollView.getHeight() + scrollView.getScrollY());
                                    terminal_textView.setText(terminal.getTerminalOutput());
                                    System.out.println(atBottom);

                                    terminal_textView.invalidate();
                                    scrollView.invalidate();
                                    //scrollView.fullScroll(View.FOCUS_DOWN);

                                }
                            });
                            Thread.sleep(250);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        }


        return root;
    }


    @Override
    public void onDestroy() {
        if (terminal != null) {
            terminal.closeTerminal();
        }
        super.onDestroy();
    }


}