package com.airlock.iam.servicecontainer.app.infrastructure.webapp.util;

import com.vaadin.v7.data.Property;
import com.vaadin.v7.ui.Table;
import com.vaadin.v7.ui.Table.ColumnHeaderMode;

public class TranslatedKeyValueTable<K, V> extends Table {
   private final TranslatedKeyValueTable.Updater updater = new TranslatedKeyValueTable.Updater(this);

   public void update(String itemId, String newValue) {
      this.updater.update(itemId, newValue);
   }

   public void addKeyValuePair(K key, V value) {
      String translatedKey = ServiceContainerVaadinTranslator.translate(key.toString());
      super.addItem(new Object[]{translatedKey, value.toString()}, key);
   }

   public static <K, V> TranslatedKeyValueTable<K, V> buildTable() {
      TranslatedKeyValueTable<K, V> table = new TranslatedKeyValueTable<>();
      table.setColumnHeaderMode(ColumnHeaderMode.HIDDEN);
      table.setSizeUndefined();
      table.setColumnCollapsingAllowed(true);
      table.setPageLength(0);
      table.setImmediate(true);
      table.addContainerProperty("key", String.class, "undefined");
      table.addContainerProperty("value", String.class, "undefined");
      return table;
   }

   private static class Updater {
      private final Table table;

      public Updater(TranslatedKeyValueTable<?, ?> table) {
         this.table = table;
      }

      public void update(String itemId, String newValue) {
         Property<String> property = this.getPropertyForItemId(itemId);
         if (!((String)property.getValue()).equals(newValue)) {
            property.setValue(newValue);
         }
      }

      private Property<String> getPropertyForItemId(String itemId) {
         return this.table.getItem(itemId).getItemProperty("value");
      }
   }
}
