package com.example.surveillanceapp;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import java.net.NetworkInterface;


public class MainActivity extends AppCompatActivity {

    public static final String EXTRA_SERVER = "com.example.surveillanceapp.EXTRA_SERVER";
    public static final String EXTRA_NAME = "com.example.surveillanceapp.EXTRA_NAME";
    public static final String EXTRA_PASSWORD = "com.example.surveillanceapp.EXTRA_PASSWORD";

    private EditText textInputServerName;
    private EditText textInputUsername;
    private EditText textInputPassword;

    String textName;
    String textServer;
    String textPassword;


    private CheckBox remLogin;
    private SharedPreferences remPrefs;
    private static final String PREFS_NAME= "PrefsFile";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        remPrefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

        textInputServerName = findViewById(R.id.text_input_server);
        textInputUsername = findViewById(R.id.text_input_username);
        textInputPassword = findViewById(R.id.text_input_password);
        remLogin =  findViewById(R.id.rememberLogin);

        if(!isConnected()){

            new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle("Internet Connection Alert")
                    .setMessage("Please check your Internet Connection and try again")
                    .setPositiveButton("Close", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .show();
        }else{
            Toast.makeText(this, "Welcome", Toast.LENGTH_SHORT).show();
        }


        getPrefData();


        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v){
                validateServer();
                 validatePassword();
                 validateUsername();

                 if (remLogin.isChecked()) {
                     Boolean boolIsChecked = remLogin.isChecked();
                     SharedPreferences.Editor editor = remPrefs.edit();
                     editor.putString("pref_name", textInputUsername.getText().toString() );
                     editor.putString("pref_serverHost", textInputServerName.getText().toString() );
                     editor.putString("pref_password", textInputPassword.getText().toString() );
                     editor.putBoolean("pref_check", boolIsChecked);
                     editor.apply();
                     Toast.makeText(getApplicationContext(), "Login saved", Toast.LENGTH_SHORT).show();
                 } else {
                     remPrefs.edit().clear().apply();
                 }

                openActivityTwo();

                 textInputPassword.getText().clear();
                 textInputServerName.getText().clear();
                 textInputUsername.getText().clear();
            }
        });
    }

    private boolean isConnected(){

        ConnectivityManager connectivityManager= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();



    }



    private void getPrefData() {
        SharedPreferences sp = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        if (sp.contains("pref_name")
        ) {

            String u = sp.getString("pref_name", "not found");
            textInputUsername.setText(u.toString());
        }
        if (sp.contains("pref_serverHost")
        ) {
            String u = sp.getString("pref_serverHost", "not found");
            textInputServerName.setText(u.toString());
        }
        if (sp.contains("pref_password")
        ) {
            String u = sp.getString("pref_password", "not found");
            textInputPassword.setText(u.toString());
        }
        if (sp.contains("pref_check")
        ) {
         Boolean b= sp.getBoolean("pref_chceck", false);
         remLogin.setChecked(b);
        }
    }

    private boolean validateServer() {
        String serverInput = textInputServerName.getText().toString().trim();

        if (serverInput.isEmpty()) {
            textInputServerName.setError("Field can't be empty");
            return false;
        } else {
            textInputServerName.setError(null);
            return true;
        }
    }

    private boolean validateUsername() {
        String usernameInput = textInputUsername.getText().toString().trim();

        if (usernameInput.isEmpty()) {
            textInputUsername.setError("Field can't be empty");
            return false;
        } else if (usernameInput.length() > 15) {
            textInputUsername.setError("Username too long");
            return false;
        } else {
            textInputUsername.setError(null);
            return true;
        }
    }

    private boolean validatePassword() {
        String passwordInput = textInputPassword.getText().toString().trim();

        if (passwordInput.isEmpty()) {
            textInputPassword.setError("Field can't be empty");
            return false;
        } else {
            textInputPassword.setError(null);
            return true;
        }
    }

    public void confirmInput(View v) {
        if (!validateServer() | !validateUsername() | !validatePassword()) {
            return;
        }

        String input = "Hostname: " + textInputServerName.getText().toString();
        input += "\n";
        input += "Username: " + textInputUsername.getText().toString();
        input += "\n";
        input += "Password: " + textInputPassword.getText().toString();
        Toast.makeText(this, input, Toast.LENGTH_SHORT).show();
    }

    public void openActivityTwo() {

        EditText editServer = (EditText) findViewById(R.id.text_input_server);
        textServer= editServer.getText().toString();

        EditText editName = (EditText) findViewById(R.id.text_input_username);
        textName= editName.getText().toString();

        EditText editPassword = (EditText) findViewById(R.id.text_input_password);
        textPassword= editPassword.getText().toString();


        Intent intent = new Intent(this, ActivityTwo.class);
        intent.putExtra(EXTRA_SERVER,textServer);
        intent.putExtra(EXTRA_NAME,textName);
        intent.putExtra(EXTRA_PASSWORD,textPassword);
        startActivity(intent);
    }
}
