package ru.myitschool.work.ui.qr.result;

import android.content.Context;
import android.os.Bundle;
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 ru.myitschool.work.R;
import ru.myitschool.work.databinding.FragmentResultBinding;

public class ResultFragment extends Fragment {
    private static final String SHARED_PREFERENCES_LOGIN_PREFERENCES = "l01";
    private static final String SHARED_PREFERENCES_LOGIN_STRING = "l02";
    private static final String SHARED_PREFERENCES_CODE = "l03";


    private FragmentResultBinding binding;
    private ResultViewModel viewModel;

    public ResultFragment() {
        super(R.layout.fragment_result);
    }


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

        binding = FragmentResultBinding.bind(view);
        viewModel = new ViewModelProvider(this).get(ResultViewModel.class);


        binding.close.setOnClickListener(v -> {
            Navigation.findNavController(getView()).navigate(R.id.action_result_fragment_to_employee_fragment);

        });

        try {
            if (getContext()
                    .getSharedPreferences(SHARED_PREFERENCES_LOGIN_PREFERENCES, Context.MODE_PRIVATE)
                    .getString(SHARED_PREFERENCES_CODE, null) == null) {
                binding.result.setText(R.string.operation_was_cancelled);
            }
            viewModel.startQuery(getContext()
                    .getSharedPreferences(SHARED_PREFERENCES_LOGIN_PREFERENCES, Context.MODE_PRIVATE)
                    .getString(SHARED_PREFERENCES_LOGIN_STRING, ""), Long.valueOf(getContext()
                    .getSharedPreferences(SHARED_PREFERENCES_LOGIN_PREFERENCES, Context.MODE_PRIVATE)
                    .getString(SHARED_PREFERENCES_CODE, "")));
        } catch (Exception e) {
            binding.result.setText(R.string.operation_was_cancelled);
        }


        subscribe(viewModel);
    }

    private void subscribe(ResultViewModel viewModel) {
        viewModel.isCorrectLiveData.observe(getViewLifecycleOwner(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean value) {
                if (value) {
                    binding.result.setText(R.string.success);
                } else {
                    binding.result.setText(R.string.something_wrong);
                }
            }
        });
    }


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