import { store } from 'https://unpkg.com/@startinblox/core@0.10';
import { Sib } from "https://unpkg.com/@startinblox/core@0.10/dist/libs/Sib.js";
import { StoreMixin } from "https://unpkg.com/@startinblox/core@0.10/dist/mixins/storeMixin.js";

export const HublReactivity = {
  name: 'hubl-reactivity',
  use: [StoreMixin],
  attributes: {
    targetSrc: {
      type: String,
      default: '',
      callback: function () {
        this.subscribe();
      }
    },
    dataSrc: {
      type: String,
      default: '',
      callback: async function (value) {
        this.resourceId = null;
        if (this.nestedField) {
          const resource = store.get(value) || await store.getData(value, this.context);
          const nestedResource = await resource[this.nestedField]
          this.resourceId = nestedResource ? nestedResource['@id'] : null;
        } else {
          this.resourceId = value;
        }
        this.subscribe();
      }
    },
  },
  subscribe() {
    if (this.resourceId && this.targetSrc) {
      store.subscribeVirtualContainerTo(this.resourceId, this.targetSrc);
      store.subscribeVirtualContainerTo(this.targetSrc, this.resourceId);
    }
  }
}

Sib.register(HublReactivity);