<template>
  <v-card-text>
    <!-- compact -->
    <v-text-field
      dense
      filled
      v-if="compact"
      label="Thema"
      :value="documentation.topic"
      @input="topic=$event"
      @focusout="save"
      @keydown.enter="saveAndBlur"
    />
    <v-chip
      v-if="compact"
      outlined
      @click="$emit('open')"
    >
      Hausaufgaben: {{ truncate(documentation.homework) }}
    </v-chip>
    <v-chip
      v-if="compact"
      outlined
      @click="$emit('open')"
    >
      Gruppennotiz: {{ truncate(documentation.groupNote) }}
    </v-chip>
    <!-- not compact -->
    <!-- Are focusout & enter enough trigger? -->
    <v-text-field
      filled
      v-if="!compact"
      label="Thema"
      :value="documentation.topic"
      @input="topic=$event"
    />
    <v-textarea
      filled
      auto-grow
      v-if="!compact"
      label="Hausaufgaben"
      :value="documentation.homework"
      @input="homework=$event"
    />
    <v-textarea
      filled
      auto-grow
      v-if="!compact"
      label="Gruppennotiz"
      :value="documentation.groupNote"
      @input="groupNote=$event"
      />
  </v-card-text>
</template>

<script>
import createOrPatchMixin from "aleksis.core/mixins/createOrPatchMixin.js";
// TODO: Update createOrPatchMixin to handle createOrPatch update of cache

export default {
  name: "LessonSummary",
  mixins: [createOrPatchMixin],
  props: {
    documentation: {
      type: Object,
      required: true,
    },
    compact: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  emits: ["open"],
  data() {
    return {
      topic: "",
      homework: "",
      groupNote: "",
    };
  },
  methods: {
    truncate(str) {
      return str ?
        (str.length > 25) ? str.slice(0, 24) + ' …' : str
      : "";
    },
    save() {
      if (this.topic || this.homework || this.groupNote) {
        const topic = this.topic ? { topic: this.topic } : {};
        const homework = this.homework ? { homework: this.homework } : {};
        const groupNote = this.groupNote ? { groupNote: this.groupNote } : {};

        this.createOrPatch([{
          id: this.documentation.id,
          ...topic,
          ...homework,
          ...groupNote,
        }]);

        this.topic = "";
        this.homework = "";
        this.groupNote = "";
      }
    },
    saveAndBlur(event) {
      this.save();
      event.target.blur();
    },
  },
};
</script>