<template>
  <Modal
    :title="`Add Connection to ${childName}`"
    :isActive="isActive"
    acceptText="Add"
    rejectText="Cancel"
    @accept="addConnection()"
    @close="close()"
  >
    <div class="field">
      <label class="label">Connection Email</label>
      <input class="input" type="email" placeholder="name@zmail.com" v-model="email" />
    </div>
    <div class="field">
      <label>
        <input class="checkbox" type="checkbox" v-model="isParent" aria-label="isParent" />
        Is this a parent? {{isParent ? "Yes" : "No"}}
      </label>
    </div>
  </Modal>
</template>

<script lang="ts">
import Modal from "../../shared/components/Modal/Modal.vue";
import { mapActions } from "vuex";
export default {
  name: "AddConnectionModal",
  props: ["isActive", "childName"],
  components: {
    Modal
  },
  methods: {
    close() {
      this.reset();
      this.$emit("dismiss");
    },
    reset() {
      this.email = "";
      this.isParent = false;
    },
    addConnection() {
      // validate email
      if (!validateEmail(this.email)) {
        this.notify({
          message: "Please provide a valid email",
          level: "warning"
        });
      } else {
        this.$emit("createNewConnection", {
          email: this.email,
          is_parent: this.isParent
        });

        this.reset();
      }
    },
    ...mapActions(["notify"])
  },
  data() {
    return {
      email: "",
      isParent: false
    };
  }
};

function validateEmail(email) {
  var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(email);
}
</script>
