package org.mercury_im.messenger.data.repository;

import org.mercury_im.messenger.data.mapping.GroupChatMapping;
import org.mercury_im.messenger.data.model.GroupChatModel;
import org.mercury_im.messenger.data.repository.dao.GroupChatDao;
import org.mercury_im.messenger.util.Optional;
import org.mercury_im.messenger.entity.Account;
import org.mercury_im.messenger.entity.chat.GroupChat;
import org.mercury_im.messenger.util.ThreadUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.inject.Inject;
import javax.inject.Named;

import io.reactivex.Completable;
import io.reactivex.Maybe;
import io.reactivex.Observable;
import io.reactivex.Scheduler;
import io.reactivex.Single;
import io.requery.Persistable;
import io.requery.query.ResultDelegate;
import io.requery.reactivex.ReactiveEntityStore;

public class XmppGroupChatRepository
        extends RequeryRepository
        implements GroupChatRepository {

    private final GroupChatMapping groupChatMapping;

    private final GroupChatDao dao;

    @Inject
    public XmppGroupChatRepository(
            ReactiveEntityStore<Persistable> data,
            @Named(value = ThreadUtils.SCHEDULER_IO) Scheduler subscriberScheduler,
            @Named(value = ThreadUtils.SCHEDULER_UI) Scheduler observerScheduler,
            GroupChatMapping groupChatMapping) {
        super(data, subscriberScheduler, observerScheduler);
        this.groupChatMapping = groupChatMapping;
        this.dao = new GroupChatDao(data);
    }

    @Override
    public Single<GroupChat> insertGroupChat(GroupChat chat) {
        return Single.just(chat)
                .map(groupChatMapping::toModel)
                .flatMap(dao::insert)
                .map(model -> groupChatMapping.toEntity(model, chat))
                .subscribeOn(subscriberScheduler())
                .observeOn(observerScheduler());
    }

    @Override
    public Observable<Optional<GroupChat>> observeGroupChat(UUID chatId) {
        return dao.get(chatId).observableResult()
                .map(result -> new Optional<>(result.firstOrNull()))
                .map(groupChatMapping::toEntity)
                .subscribeOn(subscriberScheduler())
                .observeOn(observerScheduler());
    }

    @Override
    public Maybe<GroupChat> getGroupChat(UUID chatId) {
        return dao.get(chatId).maybe()
                .map(groupChatMapping::toEntity)
                .subscribeOn(subscriberScheduler())
                .observeOn(observerScheduler());
    }

    @Override
    public Single<GroupChat> getOrCreateGroupChat(Account account, String roomAddress) {
        return getGroupChatByRoomAddress(account, roomAddress)
                .switchIfEmpty(Single.just(new GroupChat())
                        .map(chat -> {
                            chat.setAccount(account);
                            chat.setRoomAddress(roomAddress);
                            return chat;
                        })
                        .flatMap(this::insertGroupChat))
                .subscribeOn(subscriberScheduler())
                .observeOn(observerScheduler());
    }

    @Override
    public Observable<Optional<GroupChat>> observeGroupChatByRoomAddress(UUID accountId, String roomAddress) {
        return dao.get(accountId, roomAddress).observableResult()
                .map(result -> new Optional<>(result.firstOrNull()))
                .map(groupChatMapping::toEntity)
                .subscribeOn(subscriberScheduler())
                .observeOn(observerScheduler());
    }

    @Override
    public Maybe<GroupChat> getGroupChatByRoomAddress(UUID accountId, String roomAddress) {
        return dao.get(accountId, roomAddress).maybe()
                .map(groupChatMapping::toEntity)
                .subscribeOn(subscriberScheduler())
                .observeOn(observerScheduler());
    }

    @Override
    public Observable<List<GroupChat>> observeAllGroupChats() {
        return dao.getAll().observableResult()
                .map(ResultDelegate::toList)
                .map(this::modelsToEntities)
                .subscribeOn(subscriberScheduler())
                .observeOn(observerScheduler());
    }

    @Override
    public Observable<List<GroupChat>> observeAllGroupChatsOfAccount(UUID accountId) {
        return data().select(GroupChatModel.class)
                .where(GroupChatModel.ACCOUNT_ID.eq(accountId))
                .get().observableResult()
                .map(ResultDelegate::toList)
                .map(this::modelsToEntities)
                .subscribeOn(subscriberScheduler())
                .observeOn(observerScheduler());
    }

    private List<GroupChat> modelsToEntities(List<GroupChatModel> models) {
        List<GroupChat> entities = new ArrayList<>(models.size());
        for (GroupChatModel model : models) {
            entities.add(groupChatMapping.toEntity(model));
        }
        return entities;
    }

    @Override
    public Single<GroupChat> updateGroupChat(GroupChat chat) {
        return dao.get(chat.getId()).maybe().toSingle()
                .map(model -> groupChatMapping.toModel(chat, model))
                .flatMap(data()::update)
                .map(model -> groupChatMapping.toEntity(model, chat))
                .subscribeOn(subscriberScheduler())
                .observeOn(observerScheduler());
    }

    @Override
    public Single<GroupChat> upsertGroupChat(GroupChat chat) {
        return dao.get(chat.getId()).maybe()
                .switchIfEmpty(Single.just(chat).map(groupChatMapping::toModel)
                        .flatMap(dao::insert))
                .map(model -> groupChatMapping.toModel(chat, model))
                .flatMap(data()::update)
                .map(model -> groupChatMapping.toEntity(model, chat))
                .subscribeOn(subscriberScheduler())
                .observeOn(observerScheduler());
    }

    @Override
    public Completable deleteGroupChat(UUID chatId) {
        return dao.delete(chatId).ignoreElement()
                .subscribeOn(subscriberScheduler())
                .observeOn(observerScheduler());
    }
}
