<style>
  mini-br {
    border-width: 1px;
  }
</style>
<template>
  <div class='route_container'>
    <modal-window
      v-model='picture.showProfilePictureModal'
      :loading='picture.loading'
      width='25rem'
      style="z-index: 99;"
      @input='hideProflePictureModal'
    >
      <div slot="header">
        Add a team profile picture
      </div>
      <div
        slot='main'
        class='card-content'
        :class='{ "profile_picture_modal--picture.dragging": picture.dragging  }'
        @dragover='handleDragOver'
        @drkagend='picture.dragging = false'
        @drkgleave='picture.dragging = false'
        @drop='handleFileDrop'
      >
        <div class='h3'>Add a profile picture</div>
        <p class='p--condensed'>
          Drag and drop an image or<br>
          <label class='button profile_picture_modal__upload_button'>
            <input type='file' accept='image/*' @change='processImage($event.target.files[0])'>
            Upload image
          </label>
        </p>
        <div class='profile_picture_modal__drag_area'>
					<span
            v-if='!picture.dataURL'
            class='profile_picture_modal__drag_area__icon'
            :class='{ "profile_picture_modal__drag_area__icon--picture.dragging": picture.dragging }'
          >
						<font-awesome-icon :icon='["fa", "cloud-upload-alt"]' />
					</span>
          <div
            class='profile_picture_modal__drag_area__image picture_circle'
            :style='{ "background-image": "url(" + picture.dataURL + ")" }'
            v-else
          ></div>
        </div>
      </div>
      <div class='profile_picture_modal__buttons' slot='footer'>
        <button
          class='button button--modal button--green'
          :class='{ "button--disabled": !picture.dataURL }'
          @click='uploadProfilePicture'
        >
          Upload picture
        </button>
        <button class='button button--modal' @click='hideProflePictureModal'>Cancel</button>
      </div>
    </modal-window>
    <h1>{{team.name}} General</h1>
    <div>
      <h3>Name:</h3>
      <b-input
               :placeholder='team.name'
               maxlength="30"
               :value="teamGeneral.name"
               v-model='teamGeneral.name'
               :error='teamGeneral.nameError'
      ></b-input>
      <h3>Description:</h3>
      <b-input
        :placeholder='team.description'
        maxlength="256"
        :value="team.description"
        v-model='teamGeneral.description'
        :error='teamGeneral.descriptionError'
      ></b-input>
      <b-button
        class='button is-info'
        :loading='teamGeneral.loading'
        @click='saveTeam'
      >
        Save team
      </b-button>
    </div>
    <div>
      <h2>Add/change Team profile picture:</h2>
      <p
        class='p--condensed profile_picture_preview picture_circle'
        :style='{ "background-image": "url(" + picture.current + ")" }'
        v-if='picture.current'
      ></p>
      <button class='button' @click='picture.showProfilePictureModal = true'>
        {{picture.current ? "Change" : "Add" }} profile picture
      </button>
      <button
        v-if='picture.current'
        class='button'
        style='margin-left: 0.5rem;'
        @click='picture.showRemoveProfilePictureModal = true'
      >
        Remove
      </button>
    </div>
  </div>
</template>

<script>
  import FancyTextarea from '../FancyTextarea'
  import ModalWindow from '../ModalWindow'

  import AjaxErrorHandler from '../../assets/js/errorHandler'
  import logger from '../../assets/js/logger'

  export default {
    name: 'settingsGeneral',
    components: {
      // eslint-disable-next-line vue/no-unused-components
      FancyTextarea,
      ModalWindow
    },
    data() {
      return {
        teamGeneral: {
          name: '',
          loading: false,
          nameError: '',
          description: '',
          descriptionError: '',
          username: '',
          usernameError: ''
        },
        picture: {
          current: null,
          showProfilePictureModal: false,
          showRemoveProfilePictureModal: false,
          dragging: false,
          dataURL: null,
          file: null,
          loading: false
        },
        team: null
      }
    },
    computed: {},
    methods: {
      uploadProfilePicture() {
        this.picture.loading = true
        let formData = new FormData()
        formData.append('picture', this.picture.file)
        this.axios
          .post('/api/v1/teams/admin/' + this.team.username + '/picture', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          })
          .then(res => {
            this.hideProflePictureModal()
            this.picture.current = res.data.picture
          })
          .catch(e => {
            this.picture.loading = false
            AjaxErrorHandler(this.$store)(e)
          })
      },
      removeProfilePicture() {
        this.axios
          .delete('/api/v1/user/' + this.$store.state.username + '/picture')
          .then(() => {
            this.picture.current = null
          })
          .catch(AjaxErrorHandler(this.$store))
      },
      hideProflePictureModal() {
        this.picture.showProfilePictureModal = false

        //Wait for transition to complete
        setTimeout(() => {
          this.picture.dataURL = null
          this.picture.loading = false
        }, 200)
      },
      handleDragOver(e) {
        e.preventDefault()
        this.picture.dragging = true
      },
      handleFileDrop(e) {
        e.preventDefault()
        this.picture.dragging = false

        if (e.dataTransfer && e.dataTransfer.items) {
          let file = e.dataTransfer.items[0]
          if (file.type.match('^image/')) {
            this.processImage(file.getAsFile())
          }
        }
      },
      processImage(file) {
        let reader = new FileReader()
        reader.readAsDataURL(file)
        this.picture.file = file
        reader.addEventListener('load', () => {
          this.picture.dataURL = reader.result
        })
      },
      capitalizeFirstLetter(value) {
        return value.toUpperCase()
      },
      saveTeam() {
        this.teamGeneral.error = ''
        this.teamGeneral.loading = true
        this.axios
          .put(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'teams/admin/modify/' + this.team.username, {
            description: this.teamGeneral.description,
            name: this.teamGeneral.name
          })
          .then(() => {
            this.teamGeneral.loading = false
            this.axios
              .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `teams/view/${this.$route.params.username}`)
              .then(res => this.team = res.data)
            this.$nextTick(() => {
              this.axios
                .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `teams/view/${this.$route.params.username}`)
                .then(res => {
                  this.teamGeneral.description = res.data.description || ''
                  this.teamGeneral.username = res.data.username
                  this.teamGeneral.name = res.data.name || ''
                })
                .catch(e => {
                  AjaxErrorHandler(this.$store)(e)
                })
            })
          })
          .catch(e => {
            this.teamGeneral.loading = false
            AjaxErrorHandler(this.$store)(e)
          })
      },
    },
    created () {
      this.axios.get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + '/' + 'userinfo')
        .then(res => {
          this.$store.commit('setUsername', res.data.username)
          this.$store.commit('setEmail', res.data.email)
          this.$store.commit('setEmailVerified', res.data.emailVerified)
          this.$store.commit('setAdmin', res.data.admin)
          this.$store.commit('setDevMode', res.data.developerMode)
        })
      this.axios
        .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `teams/view/${this.$route.params.username}`)
        .then(res => this.team = res.data)
      this.$nextTick(() => {
        this.axios
          .get(process.env.VUE_APP_APIENDPOINT + process.env.VUE_APP_APIVERSION + `/` + `teams/view/${this.$route.params.username}`)
          .then(res => {
            this.teamGeneral.description = res.data.description || ''
            this.teamGeneral.username = res.data.username
            this.teamGeneral.name = res.data.name || ''
          })
          .catch(e => {
            AjaxErrorHandler(this.$store)(e)
          })
      })
      this.$store.dispatch('setTitle', 'General Team Settings')

      logger('settingsGeneral')
    }
  }
</script>
<style lang='scss' scoped>
  @import '../../assets/scss/variables.scss';
  .profile_picture_preview {
    height: 5rem;
    width: 5rem;
  }
  .profile_picture_modal {
    padding-top: 1rem;
    transition: all 0.2s;
    @at-root #{&}--picture .dragging {
      background-color: $color__lightgray--primary;
    }
    @at-root #{&}__overlay {
      @include loading-overlay(rgba(0, 0, 0, 0.5), 0.125rem);
    }
    @at-root #{&}__upload_button input[type="file"] {
      display: none;
    }
    @at-root #{&}__drag_area {
      padding: 1rem;
      text-align: center;
      @at-root #{&}__image {
        width: 5rem;
        height: 5rem;
        display: inline-block;
        margin-top: -1rem;
      }
      @at-root #{&}__icon {
        font-size: 6rem;
        color: $color__gray--darker;
        transition: all 0.2s;
        @at-root #{&}--picture.dragging {
          transform: translateY(-0.5rem) scale(1.1);
          color: $color__gray--darkest;
        }
      }
    }
  }
  @media (max-width: $breakpoint--tablet) {
    .h1 {
      display: none;
    }
  }
</style>
