'use strict';

Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });

const polyfill = require('@remote-dom/polyfill');
const constants = require('../constants.cjs');
const internals = require('../elements/internals.cjs');
const window = require('./window.cjs');

const hooks = window.window[polyfill.HOOKS];
hooks.insertChild = (parent, node, index) => {
  const connection = internals.remoteConnection(parent);
  if (connection == null) return;
  internals.connectRemoteNode(node, connection);
  connection.mutate([[constants.MUTATION_TYPE_INSERT_CHILD, internals.remoteId(parent), internals.serializeRemoteNode(node), index]]);
};
hooks.removeChild = (parent, node, index) => {
  const connection = internals.remoteConnection(parent);
  if (connection == null) return;
  internals.disconnectRemoteNode(node);
  connection.mutate([[constants.MUTATION_TYPE_REMOVE_CHILD, internals.remoteId(parent), index]]);
};
hooks.setText = (text, data) => {
  const connection = internals.remoteConnection(text);
  if (connection == null) return;
  connection.mutate([[constants.MUTATION_TYPE_UPDATE_TEXT, internals.remoteId(text), data]]);
};

// When an attribute is updated, we will send a message to the host to update the
// attribute, but only for native HTML elements. Custom elements are expected to
// handle their own attribute updates (which is done automatically in the `RemoteElement`
// base class).

hooks.setAttribute = (element, name, value) => {
  // Custom elements need to define their own logic for handling attribute
  // updates.
  if (element.tagName.includes('-')) return;
  internals.updateRemoteElementAttribute(element, name, value);
};
hooks.removeAttribute = (element, name) => {
  // Custom elements need to define their own logic for handling attribute
  // updates.
  if (element.tagName.includes('-')) return;
  internals.updateRemoteElementAttribute(element, name);
};

exports.hooks = hooks;
