package org.mercury_im.messenger.store;

import org.jivesoftware.smack.util.PacketParserUtils;
import org.jivesoftware.smack.xml.XmlPullParser;
import org.jivesoftware.smackx.caps.cache.EntityCapsPersistentCache;
import org.jivesoftware.smackx.disco.packet.DiscoverInfo;
import org.mercury_im.messenger.data.repository.EntityCapsRepository;
import org.mercury_im.messenger.entity.caps.EntityCapsRecord;
import org.mercury_im.messenger.logging.Tags;

import java.io.StringReader;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.inject.Inject;
import javax.inject.Singleton;

import io.reactivex.disposables.CompositeDisposable;

@Singleton
public class MercuryEntityCapsStore implements EntityCapsPersistentCache {

    private static final Logger LOGGER = Logger.getLogger(Tags.TAG_DOMAIN);

    private final CompositeDisposable disposable = new CompositeDisposable();
    private final EntityCapsRepository repository;

    @Inject
    public MercuryEntityCapsStore(EntityCapsRepository entityCapsRepository) {
        this.repository = entityCapsRepository;
    }

    @Override
    public void addDiscoverInfoByNodePersistent(String nodeVer, DiscoverInfo info) {
        LOGGER.log(Level.INFO, "MercuryEntityCapsStore: addDiscoverInfoByNodePersistent: " + nodeVer);
        EntityCapsRecord record = new EntityCapsRecord();
        record.setNodeVer(nodeVer);
        record.setXml(info.toXML().toString());

        disposable.add(repository.insertEntityCapsRecord(record).subscribe());
    }

    @Override
    public DiscoverInfo lookup(String nodeVer) {
        LOGGER.log(Level.INFO, "MercuryEntityCapsStore: lookup: " + nodeVer);
        return repository.maybeGetEntityCapsRecord(nodeVer)
                .map(this::parseDiscoverInfo)
                .onErrorComplete()
                .blockingGet();
    }

    private DiscoverInfo parseDiscoverInfo(EntityCapsRecord record) throws Exception {
        XmlPullParser parser = PacketParserUtils.getParserFor(new StringReader(record.getXml()));
        return (DiscoverInfo) PacketParserUtils.parseIQ(parser);
    }

    @Override
    public void emptyCache() {
        LOGGER.log(Level.INFO, "MercuryEntityCapsStore: emptyCache.");
        // Not needed?
    }
}
