package ru.myitschool.work.ui.login;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;

import java.nio.charset.StandardCharsets;

import ru.myitschool.work.R;
import ru.myitschool.work.databinding.FragmentLoginBinding;
import ru.myitschool.work.ui.employee.EmployeeFragment;

public class LoginFragment extends Fragment {

    private static final String SHARED_PREFERENCES_LOGIN_PREFERENCES = "l01";
    private static final String SHARED_PREFERENCES_LOGIN_STRING = "l02";

    private FragmentLoginBinding binding;
    private LoginViewModel viewModel;

    public LoginFragment() {
        super(R.layout.fragment_login);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        SharedPreferences sharedPreferences = getContext().getSharedPreferences(SHARED_PREFERENCES_LOGIN_PREFERENCES, Context.MODE_PRIVATE);
        if (sharedPreferences.contains(SHARED_PREFERENCES_LOGIN_STRING)) {

            Navigation.findNavController(getView()).navigate(
                    R.id.action_login_fragment_to_employee_fragment);
        }

        binding = FragmentLoginBinding.bind(view);

        viewModel = new ViewModelProvider(this).get(LoginViewModel.class);

        binding.username.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                viewModel.onChangeLogin(s.toString());
                binding.error.setVisibility(View.GONE);
            }
        });
        binding.password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                viewModel.onChangePassword(s.toString());
                binding.error.setVisibility(View.GONE);
            }
        });

        binding.login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.startQuery();
                binding.error.setVisibility(View.GONE);
            }
        });

        subscribe(viewModel);

    }

    private void subscribe(LoginViewModel viewModel) {
        viewModel.buttonStateLiveData.observe(getViewLifecycleOwner(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean value) {
                binding.login.setClickable(value);
                binding.login.setEnabled(value);
            }
        });
        viewModel.loginStateLiveData.observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if (s.equals("Correct Login")) {
                    SharedPreferences sharedPreferences = getContext().getSharedPreferences(SHARED_PREFERENCES_LOGIN_PREFERENCES, Context.MODE_PRIVATE);
                    sharedPreferences.edit()
                            .putString(SHARED_PREFERENCES_LOGIN_STRING, "Basic " + Base64.encodeToString((binding.username.toString() + ":" + binding.password.toString()).getBytes(StandardCharsets.UTF_8), Base64.DEFAULT))
                            .apply();

                    Navigation.findNavController(getView()).navigate(
                            R.id.action_login_fragment_to_employee_fragment);
                } else if (s.equals("Incorrect Login")) {
                    binding.error.setVisibility(View.VISIBLE);
                    binding.error.setText("Error");
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        binding = null;
        super.onDestroyView();
    }
}
