package uk.gov.register.db;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import uk.gov.register.core.Entry;
import uk.gov.verifiablelog.store.MerkleLeafStore;

public class EntryMerkleLeafStore implements MerkleLeafStore {

    private final EntryQueryDAO entryDAO;
    private final EntryIteratorDAO entryIteratorDAO;

    public EntryMerkleLeafStore(EntryQueryDAO entryDAO) {
        this.entryDAO = entryDAO;
        this.entryIteratorDAO = new EntryIteratorDAO(entryDAO);
    }

    @Override
    public byte[] getLeafValue(int i) {
        return bytesFromEntry(entryIteratorDAO.findByEntryNumber(i + 1));
    }

    @Override
    public int totalLeaves() {
        return entryDAO.getTotalEntries();
    }

    private byte[] bytesFromEntry(Entry entry) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
            mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, false);

            String value = mapper.writeValueAsString(entry);
            return value.getBytes();
        } catch (JsonProcessingException e) {
            // FIXME swallow for now and return null byte
            return new byte[]{0x00};
        }
    }
}

@@ -392,17 +392,16 @@
 Store %7B%0A
-%0A
     priv
@@ -487,16 +487,55 @@
 torDAO;%0A
+    private final boolean hasEntries;%0A%0A
 %0A    pub
@@ -683,16 +683,61 @@
 ryDAO);%0A
+        this.hasEntries = totalLeaves() %3E 0;%0A
     %7D%0A%0A 
@@ -803,16 +803,29 @@
   return
+ hasEntries ?
  bytesFr
@@ -874,16 +874,35 @@
 (i + 1))
+ : new byte%5B%5D%7B0x00%7D
 ;%0A    %7D%0A

Make EntryMarkleLeafStore cater for empty db