<template>
  <Modal
    :title="`New Call`"
    :isActive="isActive"
    acceptText="Call"
    rejectText="Cancel"
    @accept="createCall()"
    @close="close()"
  >
    <div class="columns">
      <div class="column">
        Select Child:
        <div class="card">
          <div class="card-content">
            <avatar-badge
              v-for="child in user.connections.children"
              :key="child.id"
              :img="child.avatar"
              :text="child.name"
              @onClick="onChildSelected(child)"
              :isLink="true"
              :style="child_id===child.id ? `background-color:rgba(56, 181, 187, 0.19); border-radius:15px;` : ''"
            />
          </div>
        </div>
      </div>
      <div class="column">
        Select Connection:
        <div class="card">
          <div class="card-content">
            <avatar-badge
              v-for="user in connection_options"
              :key="user.id"
              :img="user.avatar"
              :text="user.name"
              @onClick="onConnectionSelected(user)"
              :isLink="true"
              :style="connection_id===user.id ? `background-color:rgba(56, 181, 187, 0.19); border-radius:15px` : ''"
            />
          </div>
        </div>
      </div>
    </div>
  </Modal>
</template>

<script lang="ts">
import Modal from "../../shared/components/Modal/Modal.vue";
import AvatarBadge from "./AvatarBadge.vue";
import { mapActions, mapGetters } from "vuex";
export default {
  name: "ConfigureNewCallModal",
  props: ["isActive"],
  components: {
    Modal,
    AvatarBadge
  },
  computed: {
    ...mapGetters(["user"])
  },
  methods: {
    close() {
      this.reset();
      this.$emit("dismiss");
    },
    onChildSelected(child) {
      this.child_id = child.id;
      this.connection_options = child.connections;
    },
    onConnectionSelected(user) {
      this.connection_id = user.id;
    },
    reset() {
      this.connection_id = "";
      this.child_id = false;
    },
    validate() {
      if (!this.child_id || !this.connection_id) return false;
      const children = this.user.connections.children;
      for (const child of children) {
        for (const connection of child.connections) {
          if (connection.id === this.connection_id) return true;
        }
      }
      return false;
    },
    createCall() {
      if (!this.validate()) {
        this.notify({
          message: "Please select a child and a user",
          level: "warning"
        });
      } else {
        this.$emit("newCall", {
          connection_id: this.connection_id,
          child_id: this.child_id
        });

        this.reset();
      }
    },
    ...mapActions(["notify"])
  },
  data() {
    return {
      connection_id: null,
      child_id: null,
      connection_options: []
    };
  }
};
</script>
