<template>
  <div class="lanaya-date" @click="clickHandler" :style="widthStyle">
    <span class="lanaya-date__input">{{dateStr}}</span>
  </div>
</template>

<script>
import { dateFormatter } from './../../src/utils/utils';
import { DatePickerUtils } from './datePickerUtils';

export default {
  name: 'LDate',
  data () {
    return {
      showedDate: null,
      showPicker: false
    };
  },
  methods: {
    clickHandler () {
      this.showPicker = !this.showPicker;
      if (this.showPicker) {
        DatePickerUtils.createPicker({
          date: this.showedDate || new Date(),
          withTime: this.withTime
        }, this);
      } else {
        DatePickerUtils.destroyPicker();
      }
    }
  },
  model: {
    prop: 'dateValue',
    event: 'dateValueChange'
  },
  props: {
    withTime: {
      type: Boolean,
      default: true
    },
    dateValue: {
      type: null
    },
    format: {
      type: String,
      default: 'yyyy-MM-dd HH:mm:ss'
    },
    width: {
      type: String,
      default: '100%'
    }
  },
  beforeCreate () {
    this.$on('destroyPicker', d => {
      DatePickerUtils.destroyPicker();
    });
    this.$on('pickDate', function (d) {
      this.showedDate = d;
      this.$emit('destroyPicker');
      this.$emit('dateValueChange', this.showedDate);
    });
    this.$on('datePickerHasDestroyed', _ => {
      this.showPicker = !this.showPicker;
    });
  },
  mounted () {
    if (typeof this.dateValue === 'undefined' || this.dateValue === null) {
      this.showedDate = null;
    } else {
      let propDate = new Date(this.dateValue);
      if (propDate.toString() === 'Invalid Date') {
        this.showedDate = null;
      } else {
        this.showedDate = propDate;
      }
    }
  },
  computed: {
    widthStyle () {
      return {
        width: this.width
      };
    },
    dateStr () {
      return this.showedDate ? dateFormatter(this.format, this.showedDate) : '';
    }
  }
};
</script>
