class Message {
  static is(value) {
    return typeof value == "object" && typeof value.destination == "string" && value.content != undefined;
  }
  static send(message, content, context) {
    if (Message.is(message) && context == undefined) {
      context = content;
      if (!context)
        context = window;
      const destination = message.destination.split("#", 2);
      message = { destination: destination[1], content: message.content };
      context.postMessage(message, destination[0]);
    }
    else if (typeof context != "string") {
      if (!context)
        context = window;
      if (typeof message == "string")
        Message.send({ destination: message, content }, context);
    }
  }
  static listen(origin, handle, context) {
    const splitted = origin.split("#", 2);
    let destination = "";
    if (splitted.length == 2) {
      origin = splitted[0];
      destination = splitted[1];
    }
    (context || window).addEventListener("message", (e) => {
      const message = e.data;
      if (Message.is(message) &&
        (origin == "*" || e.origin == origin) &&
        (destination == "" || message.destination == destination))
        handle(message.destination, message.content);
    });
  }
}

class Trigger {
  static is(value) {
    return typeof value == "object" && typeof value.name == "string";
  }
}

export { Message as M, Trigger as T };
