<template>
  <div>
    <div class="wrap tab-pane dash-wrap">
      <div class="row dash-heading">
        <div class="d-all m-all">
          <h1>Entities</h1>
          <p>
            Below you can view a list of all entities extracted since installing the plugin along with useful data such as the number of articles each entity has been associated with &amp; its average salience score.
          </p>
        </div>
      </div>

      <div class="row">
        <div class="bulk-delete-wrap m-all">
          <div class="input-group mb-3 upload-key-group">
            <Button
              v-if="entityIds.length >0 "
              :buttonClass="'enstract-button eb-medium text-center button-radius bulk-delete'"
              :buttonName="'Bulk Delete'"
              :ButtonType="'button'"
              @click.native="changeBulkAction"
            ></Button>
          </div>
        </div>

        <div class="f-right">
              <div class="search-input-group mb-3 upload-key-group">
                <Search v-model="query" @fetchEntities="fetchEntities"></Search>
              </div>

              <Pagination
                :meta="meta"
                v-on:pagination:switched="fetchEntities"
              ></Pagination>
        </div>
      </div>

      <div class="table-responsive">
      <table class="table table-hover">
        <thead>
          <tr>
            <th scope="col">
            <label class="bulk-checkbox">
              <input
                type="checkbox"
                class="enstract-checkbox"
                @click="selectAll"
                v-model="allSelected"
              />
              <span class="checkmark heading-check"></span>
            </label>
            </th>
            <th scope="col" @click="sortBy('name')">Name</th>
            <th scope="col" @click="sortBy('slug')" class="hide-from-tablet">Slug</th>
            <th scope="col" @click="sortBy('salience')" class="text-center">
              Avg Salience
            </th>
            <th scope="col" @click="sortBy('count')" class="text-center">
              Article Count
            </th>
            <th scope="col" class="text-right"></th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(entity, index) in entities" :key="entity.name">
            <th scope="row">
            <label class="enstract-checkboxes">
              <input
                type="checkbox"
                class="enstract-checkbox"
                v-model="entityIds"
                @click="select(entity)"
                :value="entity.id"
              />
              <span class="checkmark"></span>
            </label>
            </th>
            <td>{{ entity.name }}</td>
            <td class="hide-from-tablet">{{ entity.slug }}</td>
            <td class="text-center">{{ entity.salience }}</td>
            <td class="text-center">{{ entity.article_count }}</td>
            <td class="text-right">
              <div class="row-options">
                <a
                  :href="site_origin+'/bluearray/entities/'+entity.slug"
                  target="_blank"
                  ><i class="far fa-eye"></i></a>
                <a href="#" @click.prevent="editEntity(entity, index, $event)"
                  ><i class="fas fa-pencil-alt" aria-hidden="true"></i
                ></a>
                <a href="#" @click.prevent="deleteEntity(entity, index, $event)"
                  ><i class="far fa-trash-alt trash-i"></i
                ></a>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="table-mobile">
      <div class="table-item" v-for="(entity, index) in entities" :key="entity.name">

        <div class="row stats">
          <div class="item-name">
            <strong>Name:</strong> {{ entity.name }}
          </div>

          <div class="item-salience">
            <i class="fal fa-star"></i> {{ entity.salience || 'N/A' }}
          </div>
        </div>

        <div class="row stats">
          <div class="item-slug">
            <strong>Slug:</strong> {{ entity.slug }}
          </div>

          <div class="item-count">
            <i class="fal fa-books"></i> {{ entity.article_count }}
          </div>
        </div>

        <div class="row options">
          <a
          class="color-black"
          :href="site_origin+'/bluearray/entities/'+entity.slug"
          target="_blank"
          ><i class="far fa-eye"></i> View</a>

          <a href="#" @click.prevent="editEntity(entity, index, $event)" class="color-black"
          ><i class="fas fa-pencil-alt" aria-hidden="true"></i
          >Edit</a>

          <a href="#" @click.prevent="deleteEntity(entity, index, $event)" class="color-red"
          ><i class="far fa-trash-alt trash-i"></i
          >Delete</a>

          </div>
      </div>
    </div>

    </div>

    <!-- Modal popup -->
    <Popup
      :isModalVisible="isModalVisible"
      :popup_title="popup_title"
      :popup_type="popup_type"
      :popup_content="popup_content"
      @updateEntity="updateEntity"
      @destroyEntity="destroyEntity"
      @closeEditEntity="closeEditEntity"
    >
    </Popup>
  </div>
</template>

<script>
import api from "../../mixins/api";
import Pagination from "../includes/Pagination";
import Search from "./includes/Search";
import Popup from "../includes/Popup";
import Button from "../includes/Button";

export default {
  mixins: [api],
  components: {
    Pagination,
    Search,
    Popup,
    Button,
  },
  data() {
    return {
      bulk_actions: "bulk_actions",
      isModalVisible: false,
      entities: [],
      sortRevers: false,
      meta: [],
      selected: [],
      allSelected: false,
      entityIds: [],
      entityNames: [],
      entitiesArray: [],
      query: "",
      popup_title: "",
      popup_type: "",
      popup_content: [],
      site_origin: "",
      PopupIndex: null,
    };
  },
  beforeMount() {
    this.fetchEntities();
  },
  computed: {
    // Not using this right now.
    filteredEntites() {
      return this.entities.filter((row) => {
        return Object.keys(row).some((key) => {
          return String(row[key]).indexOf(this.query) > -1;
        });
      });
    },
  },
  mounted() {
    this.site_origin = window.location.origin;
  },
  methods: {
    async fetchEntities(page = 1) {
      const data = {
        searchq: this.query,
      };
      const params = {
        page,
      };

      const response = await this.api(
        "post",
        window.apipath + "/entities",
        data,
        params,
        1
      );

      if (response.status == 200) {
        this.mergeSlugs(response.data.data);
        this.meta = response.data.meta;
      } else {
        this.isSubmitted = false;
      }
    },
    async mergeSlugs(entities) {
      const data = {
        entities: entities,
      };

      const response = await this.api(
        "post",
        wpApiSettings.root + "enstract/v1/enstract/entities/slugs",
        data,
        0,
        1
      );

      if (response.status == 200) {
        this.entities = response.data;
        console.log(this.entities);
      } else {
        this.isSubmitted = false;
      }
    },
    sortBy(key) {
      this.sortRevers = !this.sortRevers;

      this.entities.sort((a, b) => {
        return this.sortRevers
          ? a[key] < b[key]
            ? 1
            : -1
          : a[key] > b[key]
          ? 1
          : -1;
      });
    },
    selectAll() {
      this.entityIds = [];
      this.entitiesArray = [];
      this.entityNames = [];

      if (!this.allSelected) {
        this.entities.map((entity) => {
          this.entityIds.push(entity.id);
          this.entitiesArray.push({ id: entity.id, term_id: entity.term_id });
          this.entityNames.push(entity.name);
        });
      }

    },
    select(entity) {
      this.allSelected = false;
      if(this.entitiesArray.filter(p => p.id == entity.id).length !== 0 && this.entityIds.filter(p => p == entity.id).length !== 0 && this.entityNames.filter(p => p == entity.name).length !== 0) {
        
        let entities_index = this.entitiesArray.findIndex(x => x.id === entity.id);
        let idsindex = this.entityIds.findIndex(x => x === entity.id);
        let nameindex = this.entityNames.findIndex(x => x === entity.name);

        this.$delete(this.entitiesArray, entities_index)
        this.$delete(this.entityIds, idsindex)
        this.$delete(this.entityNames, nameindex)
      } else {
          this.entityIds.push(entity.id);
          this.entitiesArray.push({ id: entity.id, term_id: entity.term_id });
          this.entityNames.push(entity.name);
      }

    },
    changeBulkAction() {
      this.popup_title = "Are you sure?";
      this.popup_type = "delete_bulk";
      this.popup_content = this.entityNames;
      this.isModalVisible = true;
    },
    editEntity(entity, index, e) {
      e.preventDefault();
      this.popup_title = "Edit Entity";
      this.popup_type = "edit";
      this.popup_content = entity;
      this.isModalVisible = true;
      this.PopupIndex = index;
    },
    deleteEntity(entity, index, e) {
      e.preventDefault();
      this.popup_title = "Are you sure?";
      this.popup_type = "delete";
      this.popup_content = entity;
      this.isModalVisible = true;
      this.PopupIndex = index;
    },
    async updateEntity(values) {
      const data = {
        entity: values,
      };

      const response = await this.api(
        "post",
        wpApiSettings.root + "enstract/v1/enstract/entities/update",
        data,
        0,
        1
      );
      if (response.status == 200) {
        let value = {
          id: values.id,
          name: values.name,
          slug: values.slug,
          salience: values.salience,
          article_count: values.article_count,
          post_id: values.post_id,
          term_id: values.term_id,
          user_id: values.user_id,
        };

        this.isModalVisible = false;
        this.entities.$set(this.PopupIndex, value);
      } else {
        this.isSubmitted = false;
        console.log(e);
      }
    },
    async destroyEntity(values) {
      if (this.popup_type == "delete_bulk") {
        var arry = this.entitiesArray;
      } else {
        this.entitiesArray = [];
        this.entitiesArray.push({ id: values.id, term_id: values.term_id });
        var arry = this.entitiesArray;
      }

      const data = {
        entities: arry,
      };
      const response = await this.api(
        "post",
        wpApiSettings.root + "enstract/v1/enstract/entities/delete",
        data,
        0,
        1
      );

      if (response.status == 200) {
        this.isModalVisible = false;

        if (this.popup_type == "delete_bulk") {
          this.allSelected = false;
          this.entityIds = [];
          this.entitiesArray = [];
          this.entityNames = [];
          this.fetchEntities();
        } else {
          this.$delete(this.entities, this.PopupIndex);
        }
      } else {
        this.isSubmitted = false;
      }
    },
    closeEditEntity() {
      this.isModalVisible = false;
      this.PopupIndex = null;
    },
  },
};
</script>
