<template>
  <div class="general-information">
    <b-form id="edit_form" @submit.stop.prevent="onSubmit">
      <coscine-form-group
        :mandatory="true"
        labelFor="ResourceName"
        :label="$t('ResourceNameLabel')"
      >
        <b-form-input
          id="ResourceName"
          v-model="$v.resource.ResourceName.$model"
          @input="translateResourceNameToDisplayName"
          aria-describedby="ResourceNameHelp"
          :state="
            $v.resource.ResourceName.$dirty
              ? !$v.resource.ResourceName.$error
              : null
          "
          :placeholder="$t('ResourceName')"
          maxlength="200"
          required="required"
        />
        <div class="invalid-tooltip">{{ $t("ResourceNameHelp") }}</div>
      </coscine-form-group>
      <coscine-form-group
        :mandatory="true"
        labelFor="DisplayName"
        :label="$t('DisplayNameLabel')"
      >
        <b-form-input
          id="DisplayName"
          v-model="$v.resource.DisplayName.$model"
          @input="lockDisplayName"
          aria-describedby="DisplayNameHelp"
          :state="
            $v.resource.DisplayName.$dirty
              ? !$v.resource.DisplayName.$error
              : null
          "
          :placeholder="$t('DisplayName')"
          maxlength="25"
          required="required"
        />
        <div class="invalid-tooltip">{{ $t("DisplayNameHelp") }}</div>
      </coscine-form-group>
      <coscine-form-group
        :mandatory="true"
        labelFor="Description"
        :label="$t('ResourceDescriptionLabel')"
      >
        <b-form-textarea
          id="Description"
          v-model="$v.resource.Description.$model"
          aria-describedby="ResourceDescriptionHelp"
          :state="
            $v.resource.Description.$dirty
              ? !$v.resource.Description.$error
              : null
          "
          :placeholder="$t('ResourceDescription')"
          maxlength="5000"
          required="required"
        />
        <div class="invalid-tooltip">{{ $t("ResourceDescriptionHelp") }}</div>
      </coscine-form-group>
      <coscine-form-group
        :mandatory="true"
        labelFor="Disciplines"
        :label="$t('ResourceDisciplineLabel')"
        class="abc"
      >
        <multiselect
          id="Disciplines"
          v-model="resource.Disciplines"
          :options="disciplines"
          :multiple="true"
          :hide-selected="true"
          :label="disciplineLabel"
          :track-by="disciplineLabel"
          :placeholder="$t('ResourceDiscipline')"
        >
        </multiselect>
      </coscine-form-group>
      <coscine-form-group
        labelFor="Keywords"
        :label="$t('ResourceKeywordsLabel')"
      >
        <multiselect
          id="Keywords"
          v-model="resource.Keywords"
          :options="keywordoptions"
          :placeholder="$t('ResourceKeywords')"
          :multiple="true"
          :taggable="true"
          :tag-placeholder="$t('TagPlaceholder')"
          @tag="addTag"
        ></multiselect>
      </coscine-form-group>
      <coscine-form-group
        :mandatory="true"
        labelFor="Visibility"
        :label="$t('ResourceVisibilityLabel')"
      >
        <b-form-radio-group
          v-model="resource.Visibility"
          :options="visibilities"
          name="radios-stacked"
          stacked
        ></b-form-radio-group>
      </coscine-form-group>
      <coscine-form-group
        labelFor="ResourceLicense"
        :label="$t('ResourceLicenseLabel')"
        :info="true"
      >
        <template #popover>
          {{ $t("popoverLicense") }}
          <b-link
            href="https://help.itc.rwth-aachen.de/service/b2b7729fd93f4c7080b475776f6b5d87/article/7812e3fcd3a241808f5b91e11b6ca3a9/"
            target="_blank"
            >{{ $t("help") }}</b-link
          >
        </template>
        <b-form-select
          id="ResourceLicense"
          v-model="resource.License"
          :options="licenses"
          :placeholder="$t('ResourceLicense')"
        >
          <template v-slot:first>
            <option :value="null">
              {{ $t("SelectResourceLicense") }}
            </option>
          </template>
        </b-form-select>
      </coscine-form-group>
      <coscine-form-group
        labelFor="UsageRights"
        :label="$t('ResourceUsageRightsLabel')"
        :info="true"
      >
        <template #popover>
          {{ $t("popoverUsageRights") }}
          <b-link
            href="https://help.itc.rwth-aachen.de/service/b2b7729fd93f4c7080b475776f6b5d87/article/7812e3fcd3a241808f5b91e11b6ca3a9/"
            target="_blank"
            >{{ $t("help") }}</b-link
          >
        </template>
        <b-form-input
          id="UsageRights"
          v-model="$v.resource.UsageRights.$model"
          aria-describedby="UsageRightsHelp"
          :state="
            $v.resource.UsageRights.$dirty
              ? !$v.resource.UsageRights.$error
              : null
          "
          :placeholder="$t('ResourceUsageRights')"
          maxlength="500"
          required="required"
        />
        <div class="invalid-tooltip">{{ $t("ResourceUsageRightsHelp") }}</div>
      </coscine-form-group>
    </b-form>
    <b-button
      @click.prevent="back"
      class="btn btn-secondary"
      variant="outline-primary"
      >{{ $t("back") }}</b-button
    >
    <b-button
      @click.prevent="next"
      class="btn btn-secondary float-right"
      variant="outline_primary"
      :disabled="this.$v.$invalid"
      >{{ $t("next") }}</b-button
    >
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import {
  ProjectApi,
  ProjectRoleApi,
  DisciplineApi,
  VisibilityApi,
  LicenseApi,
} from "@coscine/api-connection";

import { validationMixin } from "vuelidate";
import {
  required,
  minLength,
  maxLength,
  integer,
} from "vuelidate/lib/validators";

import BootstrapVue from "bootstrap-vue";

import Multiselect from "vue-multiselect";
import "vue-multiselect/dist/vue-multiselect.min.css";
Vue.component("multiselect", Multiselect);

import { LanguageUtil } from "@coscine/app-util";
import { CoscineFormGroup } from "@coscine/component-library";
import "@coscine/component-library/dist/index.css";

function checkKeywords(value: any) {
  // check if the total sum of characters for keywords is <= 1000
  let count = 0;
  if (typeof value === "string") {
    count = value.length;
  } else if (value !== undefined) {
    for (const keyword of value) {
      count += keyword.length;
    }
  }
  return count <= 1000;
}

export default Vue.extend({
  mixins: [validationMixin],
  name: "GeneralInfo",
  components: {
    CoscineFormGroup,
  },
  validations: {
    resource: {
      ResourceName: {
        required,
        maxLength: maxLength(200),
      },
      DisplayName: {
        required,
        maxLength: maxLength(25),
      },
      Description: {
        required,
        maxLength: maxLength(5000),
      },
      Disciplines: {
        required,
      },
      Licence: {},
      Keywords: {
        checkKeywords,
      },
      Visibility: {
        required,
      },
      UsageRights: {
        maxLength: maxLength(500),
      },
    },
  },
  props: {
    resource: Object,
    projectId: String,
    isOwner: Boolean,
  },
  data() {
    return {
      displayNameIsLocked: false,
      licenses: [] as Array<unknown>,
      disciplines: [] as Array<unknown>,
      visibilities: [] as Array<unknown>,
      keywordoptions: [] as Array<unknown>,
      disciplineLabel: "displayNameEn",
    };
  },
  methods: {
    back() {
      this.$emit("back");
    },
    next() {
      this.$v.$touch();
      if (!this.$v.$invalid) {
        this.$emit("next");
      }
    },
    formIsValid() {
      this.$v.$touch();
      if (!this.$v.$invalid) {
        return true;
      }
      return false;
    },
    addTag(newTag: any) {
      this.resource.Keywords.push(newTag);
      this.keywordoptions.push(newTag);
    },
    translateResourceNameToDisplayName() {
      if (this.displayNameIsLocked) {
        return;
      }
      if (this.resource.ResourceName.length >= 25) {
        this.resource.DisplayName = this.resource.ResourceName.substring(0, 25);
      } else {
        this.resource.DisplayName = this.resource.ResourceName;
      }
    },
    lockDisplayName() {
      this.displayNameIsLocked = true;
    },
  },
  beforeMount() {
    if (LanguageUtil.getLanguage() === "en") {
      this.disciplineLabel = "displayNameEn";
    } else {
      this.disciplineLabel = "displayNameDe";
    }
  },
  mounted() {
    VisibilityApi.getVisibilities((response: any) => {
      for (const datum of response.data) {
        if (
          this.resource.Visibility.displayName === "" &&
          datum.displayName === "Project Members"
        ) {
          this.resource.Visibility = datum;
        }
        this.visibilities.push({ value: datum, text: datum.displayName });
      }
    });

    DisciplineApi.getDisciplines((response: any) => {
      this.disciplines = [];
      for (const datum of response.data) {
        this.disciplines.push(datum);
      }
    });

    LicenseApi.getLicenses((response: any) => {
      this.licenses = [];
      for (const license of response.data) {
        this.licenses.push({ value: license, text: license.displayName });
      }
      this.licenses.sort((a: any, b: any) =>
        a.text < b.text ? -1 : a.text > b.text ? 1 : 0
      );
    });

    this.displayNameIsLocked = false;
    ProjectApi.getProjectInformation(this.projectId, (response: any) => {
      this.resource.Disciplines = response.data.disciplines;
    });
  },
});
</script>

<style>
.general-information .multiselect {
  height: calc(1.4em + 0.75rem + 2px);
}
.general-information .multiselect__input {
  border: 0px;
  height: calc(1.4em + 0.75rem + 2px);
}
.general-information .multiselect__tags {
  border-radius: 0px;
}
.abc > div {
  max-width: 75%;
}
.general-information .multiselect__tag {
  white-space: normal;
}
.general-information .vdp-datepicker__calendar-button {
  height: calc(1.4em + 0.75rem + 2px);
}
.general-information .col-form-label {
  font-weight: bold;
}
.invalid-tooltip {
  position: absolute;
  top: 100%;
  z-index: 5;
  display: none;
  max-width: 100%;
  padding: 0.25rem 0.5rem;
  margin-top: 0.1rem;
  font-size: 0.76563rem;
  line-height: 1.4;
  color: #fff;
  background-color: rgba(204, 7, 30, 0.9);
  border-radius: 0;
}
</style>