package com.example.onetap_ssh.ui.home;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

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

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.util.Objects;

import com.example.onetap_ssh.MainActivity;
import com.example.onetap_ssh.R;
import com.example.onetap_ssh.SSH_connection;
import com.example.onetap_ssh.ui.terminal.Terminal;

public class HomeFragment extends Fragment {

    public static String user, password, ip;

    public static EditText ipInput;
    public static EditText userInput;
    public static EditText passwordInput;
    boolean isPasswordVisible = false;
    Button reboot_Button;
    Button shutdown_Button;
    Button loginButton;
    Button logoutButton;
    ImageView togglepassword;
    ImageView backgroundoverlay_bottom;




    @SuppressLint("ClickableViewAccessibility")
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        SharedPreferences prefs = requireContext().getSharedPreferences("appsettings", Context.MODE_PRIVATE);
        user = prefs.getString("user", null);
        password = prefs.getString("password", null);
        ip = prefs.getString("ip", null);

        View root = inflater.inflate(R.layout.fragment_home, container, false);
        SharedPreferences p = requireContext().getSharedPreferences("appsettings", Activity.MODE_PRIVATE);
        String Background = p.getString("Background", null);
        if (Background != null) {
            ImageView I = root.findViewById(R.id.Background);
            byte[] BA = Base64.decode(Background, Base64.DEFAULT);
            I.setImageDrawable(new BitmapDrawable(getResources(), MainActivity.scaleCenterCrop(BitmapFactory.decodeByteArray(BA, 0, BA.length), MainActivity.getScreenHeight(), MainActivity.getScreenWidth())));
            I.setScaleType(ImageView.ScaleType.CENTER_CROP);
        }
        final TextView textView = root.findViewById(R.id.text_home);
        final TextView login_data = root.findViewById(R.id.login_data);
        if (user == null || ip == null) {
            login_data.setText(R.string.please_login);
        } else {
            login_data.setText(getString(R.string.sie_sind_als_angemeldet).replace("{IP}", ip).replace("{USERNAME}", user));
        }
        userInput = (EditText) root.findViewById(R.id.loginuserInput);
        passwordInput = (EditText) root.findViewById(R.id.loginpasswordInput);
        ipInput = (EditText) root.findViewById(R.id.ipInput);
        loginButton = (Button) root.findViewById(R.id.loginButton);
        reboot_Button = (Button) root.findViewById(R.id.reboot);
        shutdown_Button = (Button) root.findViewById(R.id.shutdown);
        togglepassword = (ImageView) root.findViewById(R.id.togglepassword);
        SharedPreferences t = requireContext().getSharedPreferences("appsettings", Context.MODE_PRIVATE);
        if (user == null || ip == null) {
            loginButton.setVisibility(View.VISIBLE);
            togglepassword.setVisibility(View.VISIBLE);
            reboot_Button.setVisibility(View.GONE);
            shutdown_Button.setVisibility(View.GONE);
        } else {
            loginButton.setVisibility(View.INVISIBLE);
            togglepassword.setVisibility(View.INVISIBLE);
            ipInput.setVisibility(View.GONE);
            userInput.setVisibility(View.GONE);
            passwordInput.setVisibility(View.GONE);
            reboot_Button.setVisibility(View.VISIBLE);
            shutdown_Button.setVisibility(View.VISIBLE);
        }
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MainActivity.button_vibration) {
                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }
                if (userInput.getText().toString().trim().length() == 0 || ipInput.getText().toString().trim().length() == 0 || passwordInput.getText().toString().trim().length() == 0) {

                    AlertDialog mDialog = new AlertDialog.Builder(getContext())
                            .setTitle(getString(R.string.invalid))
                            .setMessage(getString(R.string.inputfields_cant_be_empty))

                            // 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 {
                    user = userInput.getText().toString();
                    password = passwordInput.getText().toString();
                    ip = ipInput.getText().toString();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                JSch jsch = new JSch();
                                Session session;
                                session = jsch.getSession(user, ip, 22);
                                session.setPassword(password);
                                session.setUserInfo(new Terminal.MyUserInfo() {
                                    @Override
                                    public String getPassword() {
                                        return super.getPassword();
                                    }
                                });
                                session.setConfig("StrictHostKeyChecking", "no");
                                System.out.println("CONNECT");
                                session.connect(30000);
                                Channel channel = session.openChannel("shell");
                                channel.connect(3 * 1000);
                                session.disconnect();
                                System.out.println("DISCONNECT");
                                requireActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getContext(), R.string.connecting, Toast.LENGTH_SHORT).show();
                                        SharedPreferences p = requireContext().getSharedPreferences("appsettings", Context.MODE_PRIVATE);
                                        p.edit().putString("user", user).putString("password", password).putString("ip", ip).apply();
                                        if (user == null || ip == null) {
                                            login_data.setText("");
                                            reboot_Button.setVisibility(View.GONE);
                                            shutdown_Button.setVisibility(View.GONE);
                                            backgroundoverlay_bottom.setVisibility(View.INVISIBLE);

                                        } else {
                                            login_data.setText(getString(R.string.sie_sind_als_angemeldet).replace("{IP}", ip).replace("{USERNAME}", user));
                                            logoutButton.setVisibility(View.VISIBLE);
                                            loginButton.setVisibility(View.INVISIBLE);
                                            togglepassword.setVisibility(View.INVISIBLE);
                                            ipInput.setVisibility(View.GONE);
                                            userInput.setVisibility(View.GONE);
                                            passwordInput.setVisibility(View.GONE);
                                            reboot_Button.setVisibility(View.VISIBLE);
                                            shutdown_Button.setVisibility(View.VISIBLE);
                                            backgroundoverlay_bottom.setVisibility(View.VISIBLE);
                                        }
                                    }
                                });
                            } catch (Exception e) {
                                requireActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        e.printStackTrace();
                                        AlertDialog mDialog = new AlertDialog.Builder(getContext())
                                                .setTitle(getString(R.string.unable_to_connect))
                                                .setMessage(getString(R.string.try_again))

                                                // 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();
                                    }
                                });

                            }
                        }
                    }).start();

                }
            }
        });
        logoutButton = (Button) root.findViewById(R.id.logoutButton);
        if (user == null || ip == null) {
            logoutButton.setVisibility(View.INVISIBLE);
            ipInput.setVisibility(View.VISIBLE);
            userInput.setVisibility(View.VISIBLE);
            passwordInput.setVisibility(View.VISIBLE);
            reboot_Button.setVisibility(View.GONE);
            shutdown_Button.setVisibility(View.GONE);
            backgroundoverlay_bottom.setVisibility(View.INVISIBLE);
        } else {
            logoutButton.setVisibility(View.VISIBLE);
            reboot_Button.setVisibility(View.VISIBLE);
            shutdown_Button.setVisibility(View.VISIBLE);
            backgroundoverlay_bottom.setVisibility(View.VISIBLE);
        }
        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MainActivity.button_vibration) {
                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }
                requireContext().getSharedPreferences("appsettings", Context.MODE_PRIVATE).edit().remove("ip").remove("user").remove("password").apply();
                startActivity(requireActivity().getIntent());
                requireActivity().finish();
            }
        });
        reboot_Button = (Button) root.findViewById(R.id.reboot);
        reboot_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MainActivity.button_vibration) {
                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }

                AlertDialog mDialog = new AlertDialog.Builder(getContext())
                        .setTitle(getString(R.string.restart_server))
                        .setMessage(getString(R.string.are_you_sure))

                        // 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.yes), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                if (MainActivity.button_vibration) {
                                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                                    assert vr != null;
                                    vr.vibrate(100);
                                }
                                try {

                                    Toast.makeText(getContext(), R.string.rebooting, Toast.LENGTH_SHORT).show();
                                    SSH_connection.executeRemoteCommand(ip, user, password, "reboot");
                                } catch (Exception ignored) {
                                }

                                // Continue with delete operation
                            }
                        })

                        // A null listener allows the button to dismiss the dialog and take no further action.
                        .setNegativeButton(getString(R.string.no), 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();


            }
        });
        shutdown_Button = (Button) root.findViewById(R.id.shutdown);
        shutdown_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MainActivity.button_vibration) {
                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                    assert vr != null;
                    vr.vibrate(100);
                }

                AlertDialog mDialog = new AlertDialog.Builder(getContext())
                        .setTitle(getString(R.string.shutdown_server))
                        .setMessage(getString(R.string.are_you_sure))

                        // 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(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                if (MainActivity.button_vibration) {
                                    Vibrator vr = (Vibrator) requireContext().getSystemService(Context.VIBRATOR_SERVICE);
                                    assert vr != null;
                                    vr.vibrate(100);
                                }
                                try {

                                    Toast.makeText(getContext(), R.string.shutting_down, Toast.LENGTH_SHORT).show();
                                    SSH_connection.executeRemoteCommand(ip, user, password, "shutdown now");
                                } catch (Exception ignored) {
                                }

                                // Continue with delete operation
                            }
                        })

                        // A null listener allows the button to dismiss the dialog and take no further action.
                        .setNegativeButton(getString(R.string.no), 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();

            }
        });


        if (togglepassword.getVisibility() == View.VISIBLE) {
            togglepassword.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    if (isPasswordVisible) {
                        passwordInput.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                        isPasswordVisible = false;
                    } else {
                        passwordInput.setTransformationMethod(PasswordTransformationMethod.getInstance());
                        isPasswordVisible = true;
                    }
                    return false;
                }
            });
        }

        return root;

    }

}

