<template>
  <modal>
    <template slot="header">
      <modal-input
        :placeholder="titlePlaceholder"
        :value="localContentBlock.title"
        :error="error"
        data-cy="modal-title-input"
        @input="updateTitle"
      />
      <checkbox
        :checked="localContentBlock.isAssignment"
        :item="localContentBlock"
        :label="'Auftrag'"
        class="contents-form__task"
        v-if="taskSelection"
        @input="setContentBlockType"
      />
    </template>

    <add-content-element
      :index="-1"
      class="contents-form__add"
      @add-element="addElement"
    />
    <div
      :key="index"
      class="contents-form__element"
      v-for="(element, index) in localContentBlock.contents">
      <component
        :is="type(element)"
        :class="{'contents-form__chooser': type(element) === 'content-block-element-chooser-widget'}"
        v-bind="element"
        :index="index"
        class="contents-form__element-component"
        @change-type="changeType"

        @link-change-url="changeLinkUrl"
        @link-change-text="changeLinkText"

        @text-change-value="changeTextValue"

        @document-change-url="changeDocumentUrl"

        @image-change-url="changeImageUrl"

        @video-change-url="changeVideoUrl"

        @switch-to-document="switchToDocument"

        @assignment-change-title="changeAssignmentTitle"
        @assignment-change-assignment="changeAssignmentAssignment"
      />
      <a
        class="contents-form__remove icon-button"
        @click="removeElement(index)">
        <trash-icon
          class="contents-form__trash-icon icon-button__icon"
          v-if="type(element) !== 'content-block-element-chooser-widget'"/>
      </a>

      <add-content-element
        :index="index"
        class="contents-form__add"
        @add-element="addElement"
      />
    </div>

    <div slot="footer">
      <a
        :class="{'button--disabled': disableSave}"
        class="button button--primary"
        data-cy="modal-save-button"
        @click="save">Speichern</a>
      <a
        class="button"
        @click="$emit('hide')">Abbrechen</a>
    </div>
  </modal>
</template>

<script>
  import Modal from '@/components/Modal';
  import ContentBlockElementChooserWidget from '@/components/content-forms/ContentBlockElementChooserWidget';
  import ModalInput from '@/components/ModalInput';
  import AddContentElement from '@/components/AddContentElement';
  import LinkForm from '@/components/content-forms/LinkForm';
  import VideoForm from '@/components/content-forms/VideoForm';
  import ImageForm from '@/components/content-forms/ImageForm';
  import DocumentForm from '@/components/content-forms/DocumentForm';
  import AssignmentForm from '@/components/content-forms/AssignmentForm';
  import TextForm from '@/components/content-forms/TextForm';
  import TrashIcon from '@/components/icons/TrashIcon';
  import Checkbox from '@/components/ui/Checkbox';

  import {meQuery} from '@/graphql/queries';

  export default {
    props: {
      'content-block': Object,
      'block-type': {
        type: String,
        default: 'ContentBlock'
      },
      'show-task-selection': {
        type: Boolean,
        default: false
      },
      'disable-save': {
        type: Boolean,
        default: false
      }
    },

    components: {
      Modal,
      ContentBlockElementChooserWidget,
      ModalInput,
      AddContentElement,
      LinkForm,
      VideoForm,
      ImageForm,
      DocumentForm,
      AssignmentForm,
      TextForm,
      TrashIcon,
      Checkbox
    },

    data() {
      return {
        error: false,
        localContentBlock: Object.assign({}, {
          title: this.contentBlock.title,
          contents: [...this.contentBlock.contents],
          id: this.contentBlock.id || undefined,
          isAssignment: this.contentBlock.type && this.contentBlock.type.toLowerCase() === 'task'
        }),
        me: {}
      };
    },

    apollo: {
      me: meQuery
    },

    computed: {
      titlePlaceholder() {
        return this.blockType === 'RoomEntry' ? 'Titel für Raumeintrag erfassen' : 'Titel für Inhaltsblock erfassen';
      },
      taskSelection() {
        return this.showTaskSelection && this.me.permissions.includes('users.can_manage_school_class_content');
      }
    },

    methods: {
      type(element) {
        switch (element.type) {
          case 'link_block':
            return 'link-form';
          case 'video_block':
            return 'video-form';
          case 'image_url_block':
            return 'image-form';
          case 'text_block':
            return 'text-form';
          case 'assignment':
            return 'assignment-form';
          case 'document_block':
            return 'document-form';
        }
        return 'content-block-element-chooser-widget';
      },
      _updateProperty(value, index, key) {
        const content = this.localContentBlock.contents[index];
        this.localContentBlock.contents.splice(index, 1, {
          ...content,
          value: {
            ...content.value,
            [key]: value
          }
        });
      },
      changeLinkUrl(value, index) {
        this._updateProperty(value, index, 'url');
      },
      changeLinkText(value, index) {
        this._updateProperty(value, index, 'text');
      },
      changeVideoUrl(value, index) {
        this._updateProperty(value, index, 'url');
      },
      changeImageUrl(value, index) {
        this._updateProperty(value, index, 'url');
      },
      changeDocumentUrl(value, index) {
        this._updateProperty(value, index, 'url');
      },
      changeTextValue(value, index) {
        this._updateProperty(value, index, 'text');
      },
      changeAssignmentTitle(value, index) {
        this._updateProperty(value, index, 'title');
      },
      changeAssignmentAssignment(value, index) {
        this._updateProperty(value, index, 'assignment');
      },
      removeElement(index) {
        this.localContentBlock.contents.splice(index, 1);
      },
      addElement(index) {
        this.localContentBlock.contents.splice(index + 1, 0, {
          hideAssignment: this.blockType !== 'ContentBlock'
        });
      },
      updateTitle(title) {
        this.localContentBlock.title = title;
        this.error = false;
      },
      changeType(index, type, value) {
        let el = {
          type: type,
          value: Object.assign({}, value)
        };
        switch (type) {
          case 'text_block':
            el = {
              ...el,
              value: {
                text: ''
              }
            };
            break;
          case 'link_block':
            el = {
              ...el,
              value: {
                text: '',
                url: ''
              }
            };
            break;
          case 'video_block':
            el = {
              ...el,
              value: {
                url: ''
              }
            };
            break;
          case 'document_block':
            el = {
              ...el,
              value: Object.assign({
                url: ''
              }, value)
            };
            break;
          case 'image_url_block':
            el = {
              ...el,
              value: {
                url: ''
              }
            };
            break;
        }

        this.localContentBlock.contents.splice(index, 1, el);
      },
      save() {
        if (!this.disableSave) {
          if (!this.localContentBlock.title) {
            this.error = true;
            return false;
          }
          this.$emit('save', this.localContentBlock);
        }
      },
      setContentBlockType(checked, localContentBlock) {
        this.localContentBlock.isAssignment = checked;
      },
      switchToDocument(index, value) {
        this.changeType(index, 'document_block', value);
      }
    }
  };
</script>

<style scoped lang="scss">
  @import "@/styles/_variables.scss";

  .contents-form {
    /* top level does not exist, because of the modal */

    &__element {
      display: grid;
      grid-template-columns: 1fr 50px;
      grid-auto-rows: auto;
      /*width: 95%; // reserve space for scrollbar*/
    }

    &__element-component {
      margin-bottom: 25px;
    }

    &__remove {
    }

    &__trash-icon {
    }

    &__chooser {
      grid-column: 1 / span 2;
    }

    &__add {
      grid-column: 1 / span 2;
    }

    &__task {
      margin: 15px 0 10px;
    }
  }
</style>
