package org.mercury_im.messenger.core.viewmodel.ikey;

import org.mercury_im.messenger.core.SchedulersFacade;
import org.mercury_im.messenger.core.crypto.ikey.IkeyRepository;
import org.mercury_im.messenger.core.util.Optional;
import org.mercury_im.messenger.core.viewmodel.MercuryViewModel;
import org.pgpainless.key.OpenPgpV4Fingerprint;

import java.util.UUID;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;

public class IkeyInfoViewModel implements MercuryViewModel {

    private final SchedulersFacade schedulers;
    private final IkeyRepository ikeyRepository;

    private final BehaviorSubject<Optional<OpenPgpV4Fingerprint>> fingerprint = BehaviorSubject.createDefault(new Optional<>());
    private UUID accountId;

    @Inject
    public IkeyInfoViewModel(IkeyRepository ikeyRepository, SchedulersFacade schedulersFacade) {
        this.ikeyRepository = ikeyRepository;
        this.schedulers = schedulersFacade;
    }

    public void init(UUID accountId) {
        if (this.accountId != null) {
            throw new IllegalStateException("Already initialized.");
        }

        this.accountId = accountId;
        addDisposable(ikeyRepository.loadSecretKey(accountId)
                .filter(Optional::isPresent)
                .map(Optional::getItem)
                .firstOrError()
                .map(OpenPgpV4Fingerprint::new)
                .compose(schedulers.executeUiSafeSingle())
                .map(Optional::new)
                .subscribe(this.fingerprint::onNext));
    }

    public Observable<Optional<OpenPgpV4Fingerprint>> getFingerprint() {
        return fingerprint;
    }
}
