package org.mercury_im.messenger.android.ui.account.login;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

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

import org.mercury_im.messenger.R;

import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class IkeySetupFragment extends Fragment {

    @BindView(R.id.btn_skip)
    Button skipButton;

    @BindView(R.id.btn_continue)
    Button continueButton;

    private final UUID accountId;
    private AndroidIkeySetupViewModel viewModel;

    public IkeySetupFragment(UUID accountId) {
        this.accountId = accountId;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_ikey_setup, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    public static IkeySetupFragment newInstance(UUID accountId) {
        return new IkeySetupFragment(accountId);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewModel = new ViewModelProvider(requireActivity()).get(AndroidIkeySetupViewModel.class);
        viewModel.init(accountId);

        skipButton.setOnClickListener(v ->
                getActivity().finish());

        continueButton.setOnClickListener(v -> {
            viewModel.fetchBackupElement()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSuccess(opt -> {
                        if (opt.isPresent()) {
                            ((IkeySetupNavigator) getActivity()).setupIkey(accountId);
                        } else {
                            viewModel.generateIdentityKey();
                            ((IkeySetupNavigator) getActivity()).displayInfo(accountId);
                        }
                    })
                    .subscribe();
        });
    }
}
