<template>
  <div>
    <div class="row">
      <div
        class="enstract-tab-btn text-center sidebar-btn col-md-6"
        v-bind:class="{ enstractTabActive: isEnstractActive, 'cancel-out-col': !canActivateAssignEntities}"
        @click="toggleGoogle"
      >
        Run Enstract
      </div>
      <div
        class="enstract-tab-btn text-center sidebar-btn col-md-6"
        v-if="canActivateAssignEntities"
        v-bind:class="{ enstractTabActive: isManualActive}"
        @click="toggleManual"
      >
        Assign Entities
      </div>
    </div>

    <div class="google-tab-container">
      <div class="row google-tab" v-if="showGoogle">
        <h6>Enstract your content</h6>
        <p>
          Clicking the button below will send the content of this article to the
          Enstract servers to extract &amp; inline link any Entities in
          accordance with your setting
        </p>

        <button @click="enstract" type="button" v-bind:class="{isEnstractedFinished: isEnstractedFinished}" class="col-md-6 enstract-btn">
          <div v-if="!isEnstractLoading">Enstract</div>

          <div id="loading" v-if="isEnstractLoading">
            <div class="load-wrapp">
              <div class="load-3">
                <div class="line line-white"></div>
                <div class="line line-white"></div>
                <div class="line line-white"></div>
              </div>
            </div>
          </div>
        </button>

        <div class="hostmismatch" v-if="isEnstractedFinished && hostMismatch">
            <p class="red-color">{{ enstractResponse }}</p>
        </div>

        <div class="sortEntitesResponse" v-if="isEnstractedFinished && !hostMismatch">
          <h6>Success! We found the following entities.</h6>
          <p>
            You appear to be a free user of Enstract. This restricts the number
            of entities you can inline link to two per post/page. Please select
            these below to complete the process.
          </p>

          <p>You have {{ RemainingEntities }} unique entities out of 40 left</p>

          <p class="red-color">{{ enstractResponse }}</p>

          <form @submit.prevent="saveEntities">
            <div class="entitesWrap">
              <template v-for="(entity, index) in enstracted_entities">
                <input
                  type="checkbox"
                  :id="'entity-' + index + '-item-' + entity.name"
                  :value="entity.name + '-' + index"
                  v-model="selectEntities"
                  :name="'entity-' + index + '-item-' + entity.name"
                  @change="selectEntity(entity, index, $event)"
                  class="entity_check"
                />
                <!-- :disabled="selectEntities.length > 1 && selectEntities.indexOf(n) === -1" -->
                <label :for="entity.name">{{ entity.name }}   ({{ entity.salience }}) </label><br />
              </template>
             </div>

              <button type="submit" class="col-md-6 enstract-btn">
                <div v-if="!isSavingEntitiesLoading">Save</div>

                <div id="loading" v-if="isSavingEntitiesLoading">
                  <div class="load-wrapp">
                    <div class="load-3">
                      <div class="line line-white"></div>
                      <div class="line line-white"></div>
                      <div class="line line-white"></div>
                    </div>
                  </div>
                </div>
              </button>
            </form>
        </div>
      </div>
    </div>

    <div class="assign-tab-container">
      <div class="row manual-tab" v-if="showManual">
        <h6>Assign or Unassign Entities</h6>
        <p>
          Use the checkbox list below to manually assign and/ or unassign
          certain entities.
        </p>

        <p>
          <a @click="selectAll" class="link-spacing">Select all</a>

          <a @click="deSelectAll" class="link-spacing">Deselect all</a>
        </p>

        <div class="entitesWrap">
          <template v-for="(entity, index) in entites">
            <input
              type="checkbox"
              :id="entity.name"
              v-model="entity.checked"
              @change="sortEntites($event, entity.name)"
            />
            <label :for="entity.name">{{ entity.name }} ({{ entity.salience }}) </label>
            <br />
          </template>
        </div>

        <br />

        <br clear="both" />

        <div class="entities-wrap">
          <div
            class="entities-box"
            @click="showAssignedEntities = !showAssignedEntities"
          >
            <p>Entities being assigned ({{ checkedEntites.length }})</p>

            <span v-if="!showAssignedEntities" class="entites-chev"
              ><i class="fa fa-caret-left"></i
            ></span>
            <span v-if="showAssignedEntities" class="entites-chev"
              ><i class="fa fa-caret-down"></i
            ></span>

            <template v-if="showAssignedEntities">
              <div v-for="entity in checkedEntites">
                {{ entity }}
              </div>
            </template>
          </div>

          <div
            class="entities-box"
            @click="showUnassignedEntities = !showUnassignedEntities"
          >
            <p>Entities being unassigned ({{ uncheckedEntities.length }})</p>

            <span v-if="!showUnassignedEntities" class="entites-chev"
              ><i class="fa fa-caret-left"></i
            ></span>
            <span v-if="showUnassignedEntities" class="entites-chev"
              ><i class="fa fa-caret-down"></i
            ></span>

            <template v-if="showUnassignedEntities">
              <div v-for="entity in uncheckedEntities">
                {{ entity }}
              </div>
            </template>
          </div>
        </div>

        <button
          type="button"
          class="col-md-8 enstract-btn update-entities"
          @click="processEntities"
          v-if="checkedEntites.length > 0 || uncheckedEntities.length>0"
        >
          Update Entites
        </button>

        <div class="sortEntitesResponse" v-if="isSortingEntitiesLoading">
          <template v-for="entity in sortEntitesResponse">
            <div v-html="entity"></div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import api from "../../mixins/api";

export default {
    mixins: [api],
    data() {
        return {
            entites: [],
            checkedEntites: [],
            uncheckedEntities: [],
            isEnstractLoading: false,
            isSortingEntitiesLoading: false,
            sortEntitesResponse: "",
            entityText: "",
            showGoogle: true,
            showManual: false,
            showAssignedEntities: false,
            showUnassignedEntities: false,
            isManualActive: false,
            isEnstractActive: true,
            isEnstractedFinished: false,
            enstractResponse: "",
            canActivateAssignEntities: false,
            enstracted_entities: [],
            selectEntities: [],
            isSavingEntitiesLoading: false,
            checkedAssignEntity: [],
            entites_count: null,
            hostMismatch: false,
        };
    },
    mounted() {
        window.bearer_token = this.auth;
        this.getEntites();
    },
    computed: {
        RemainingEntities: function() {
            var max = 40;
            let remainingEntities = max - this.entites_count;

            return remainingEntities;
        },
    },
    methods: {
        async getEntites() {
            const data = {
                post_id: this.post_id,
            };

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

            if (response.status == 200) {
                this.entites = response.data;
                if (Object.keys(response.data).length > 0) {
                    this.canActivateAssignEntities = true;
                }
            }
        },
        selectEntity(entity, index, e) {
            const refs = document.querySelectorAll(".entity_check");

            for (var i = 0; i < refs.length; i++)
                refs[i].onclick = this.selectiveCheck;

            if (e.target.checked == true) {
                // push to array
                this.checkedAssignEntity.push({
                    // index: entity.index,
                    name: entity.name,
                    salience: entity.salience,
                    unique: entity.unique,
                });

                if (entity.unique == 1) {
                    this.entites_count++;
                }
            } else {
                var checked_index = this.checkedAssignEntity
                    .map((el) => el.name)
                    .indexOf(entity.name);
                this.$delete(this.checkedAssignEntity, checked_index);

                if (entity.unique == 1) {
                    this.entites_count--;
                }
            }
        },
        selectiveCheck(event) {
            var max = 2;
            var checkedChecks = document.querySelectorAll(".entity_check:checked");
            if (checkedChecks.length >= max + 1) return false;
        },
        sortEntites(e, name) {
            if (e.target.checked == true) {
                var unchecked_index = this.uncheckedEntities.indexOf(name);
                this.$delete(this.uncheckedEntities, unchecked_index);

                // Push to array
                this.checkedEntites.push(name);
            } else {
                var checked_index = this.checkedEntites.indexOf(name);
                this.$delete(this.checkedEntites, checked_index);

                // Push to array
                this.uncheckedEntities.push(name);
            }
        },
        async processEntities() {
            const data = {
                post_id: this.post_id,
                body: this.fetchBody(),
                assignedEntites: this.checkedEntites,
                unassignedEntites: this.uncheckedEntities,
                referrer: rest_options.referer,
            };

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

            if (response.status == 200) {
                this.sortEntitesResponse = response.data.message;
                this.canActivateAssignEntities = true;
                this.isSortingEntitiesLoading = true;
                this.checkedEntites = [];
                this.uncheckedEntities = [];
                tinymce.activeEditor.setContent(response.data.body);
                this.getEntites();
                window.onbeforeunload = null;
            }
        },
        async enstract() {

            if(this.fetchBody().length <= 0) {
                alert('To use Enstract you need to make sure you have body text inside the editor')
                return false;
            }

            this.isEnstractLoading = true;

            const data = {
                body: this.fetchBody(),
                referrer: rest_options.referer,
                post_id: this.post_id,
            };

            var response = await this.api("post", window.apipath + "/enstract", data, 1);

            if (response.status == 200) {
                this.enstracted_entities = response.data.term_names;
                this.entites_count = response.data.entities_count;
                this.hostMismatch = false;
                this.enstractResponse = '';
                this.isEnstractedFinished = true;
                this.isEnstractLoading = false;
                this.canActivateAssignEntities = true;
                window.onbeforeunload = null;
                this.checkedAssignEntity = [];
            }

            if(response.status == 403) {
              this.isEnstractedFinished = true;
              this.isEnstractLoading = false;
              this.hostMismatch = true;
              this.enstractResponse = response.data.message;
            }

            if (response.status == 429) {
                this.isEnstractedFinished = true;
                this.isEnstractLoading = false;
                this.enstractResponse =
                    "It appears you have used up all your Enstracts for today. Come back tomorrow.";
            }
        },
        async saveEntities() {

            if (this.canActivateAssignEntities == true) {

                if (confirm("By proceding this will remove any current linked entities and replace it with your new selected entities")) {

                    this.isSavingEntitiesLoading = true;

                    const data = {
                      body: this.fetchBody(),
                      entities: this.checkedAssignEntity,
                      referrer: rest_options.referer,
                      post_id: this.post_id,
                    };

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

                    if (response.status == 200) {
                        this.isSavingEntitiesLoading = false;
                        this.isEnstractedFinished = true;
                        this.isEnstractLoading = false;
                        this.checkedEntites = [];
                        this.uncheckedEntities = [];
                        this.selectEntities = [];
                        this.checkedAssignEntity = [];
                        this.processBody(response.data);
                        window.onbeforeunload = null;
                    }
                }
            }
        },
        async processBody(data) {

            const dataconfig = {
                post_id: this.post_id,
                body: data.body,
                term_names: data.term_names,
                previous_terms: data.previous_terms,
                referrer: rest_options.referer,
            };

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

            if (response.status == 200) {
                if (response.data.reached_limit == true) {
                    this.isEnstractLoading = false;
                    this.isEnstractedFinished = false;
                    this.enstractResponse =
                        "Some entities did not make it because you reached your 40 entity limit :(";
                }
                this.isEnstractLoading = false;
                this.canActivateAssignEntities = true;
                this.isEnstractedFinished = false;
                this.checkedEntites = [];
                this.uncheckedEntities = [];
                this.getEntites();

                if (document.body.classList.contains("block-editor-page")) {
                    wp.data.dispatch('core/block-editor').resetBlocks(wp.blocks.parse(data.body));
                } else {
                    return tinymce.editors.content.setContent(data.body)
                }
            }
        },
        selectAll() {
            Object.keys(this.entites).forEach(
                function(key) {
                    this.entites[key].checked = 1;
                    this.checkedEntites.push(this.entites[key].name);
                    this.uncheckedEntities = [];
                }.bind(this)
            );
        },
        deSelectAll() {
            Object.keys(this.entites).forEach(
                function(key) {
                    this.entites[key].checked = 0;
                    this.uncheckedEntities.push(this.entites[key].name);
                    this.checkedEntites = [];
                }.bind(this)
            );
        },
        toggleGoogle() {
            this.showManual = false;
            this.showGoogle = true;
            this.isManualActive = false;
            this.isEnstractActive = true;
        },
        toggleManual() {
            this.showManual = true;
            this.showGoogle = false;
            this.isManualActive = true;
            this.isEnstractActive = false;
        },
        fetchBody() {
            if (document.body.classList.contains("block-editor-page")) {
                var b = wp.data.select("core/editor");
                return b.getCurrentPost().content;
            } else {
                return tinymce.editors.content.getContent()
            }
        },
    },
    props: ["post_id", "auth"],
};
</script>
