<template>
  <!-- placeholder div -->
  <div></div>
</template>

<script>
import moment from 'moment';
import RecoModal from '@/components/complex/RecoModal.vue';
import modalbuilders from '@/helpers/modalbuilders';
import animations from '@/animations';

export default {
  name: "RecoPostComposer",
  components: { RecoModal },
  props: {
    title: {
      type: String,
      default: ""
    },
    categories: {
      type: Array,
    },
    root: {
      type: Object,
    },
    me: {
      type: Object,
    },
    getTags: {
      type: Function,
    },
    addNewTag: {
      type: Function,
    },
    submitPost: {
      type: Function,
    },
    navigateBack: {
      type: Boolean
    },
    activeFeatures: {
      type: Array,
      default() {
        return [];
      },
    },
    excludedFeatures: {
      type: Array,
      default() {
        return [];
      },
    },
    color: {
      type: String,
      default: '#ED1556',
    },
    post:{
      type: Object,
      default(){
        return null;
      }
    },
    postLanguageChanged:{
      type: Function,
      default(){ return; }
    }
  },
  data() {
    console.log('old post: ', this.post);
    const {post} = this;
    return {
      // output data
      category: {value: "no_category", display_name: "Other", color: this.color, icon: null}, // set default category
      motto: post && post.subject ? this.post.subject : '',
      description: post && post.description ? post.description : '',
      type: 'direct',
      images: [],
      gender: post && post.gender ? post.gender : {value: "all", display_name: "All"},
      age: post && post.age ? post.age : {lower: 18, upper: 99},
      expiration: post && post.expiration ? post.expiration : {value: "forever", display_name: "Until Deletion", seconds: 9999999999},
      distance: post && post.distanceObj ? post.distanceObj : {value: "infinite", display_name: "∞ km", meters: 100000000},
      activityDateTime: null,
      maxResponses: post && post.maxResponses ? post.maxResponses : 12,
      chatType: post && post.chat_typeObj ? post.chat_typeObj : {value: "single", display_name: "Single"},
      automaticResponse: "",
      tags: post && post.tags ? post.tags : [],
      pictures: [],
      location: null,
      activityLocation: null,
      devLocation: {value: "none", display_name: "None"},
      language: post && post.language ? post.language : this.me.languages.post_language,

      // helpers
      imageURLs: post && post.images ? post.images : [],
      imageDimensions: post && post.image_dimensions ? post.image_dimensions : [],
      categorySelectModal: null,
      audienceSelectModal: null,
      expirationSelectModal: null,
      imageEditorModal: null,
      locationSelectModal: null,
      tagSelectModal: null,
      responseSelectModal: null,
      postDescriptionCreateModal: null,
      postPreviewModal: null,
      isInitialSteps: true,
      enterAnimation: animations.defaultEnter,
      leaveAnimation: animations.defaultLeave,
      isAdvancedSettings: false,
      isNextButton: true,
      currentNav: null,
    }
  },
  computed: {
    tagsTexts() {
      return {
        line1: this.tags.length+" tags are selected",
      }
    },
    audienceText() {
      const gender = this.gender.value == 'all' ? "anyone" : this.gender.value+" users";
      const age = this.age.lower == 18 && this.age.upper == 99 ? "above 18" : "between "+this.age.lower+" and "+this.age.upper;
      return "to "+gender+" "+age+".";
    },
    expirationText() {
      // const activityDateTime = !this.activityDateTime ? "The date/time of the activity is not set" : "The activity will take place on "+moment(this.activityDateTime).format('DD MMM YYYY')+" at "+moment(this.activityDateTime).format('HH:mm')
      return "for "+this.expiration.display_name.toLowerCase()+"."/*+activityDateTime+"."*/;
    },
    imagesTexts() {
      return {
        line1: "Edit uploaded images", 
        line2: this.images.length == 1 ? "1 image is added." : this.images.length+" images are added.",
      }
    },
    locationText() {
      return "only "+this.distance.display_name.toLowerCase()+" away from your current location.";
    },
    responseTypeText() {
      const people = this.maxResponses == 1 ? "One person " : this.maxResponses+" people ";
      const chat = this.chatType.value == "single" ? "in "+(this.maxResponses > 1 ? this.maxResponses : "a")+" single chat"+(this.maxResponses != 1 ? "s" : "") : "in a group chat";
      // const response = this.automaticResponse && this.maxResponses > 1 && this.chatType.value == "single" ? "Automatic response is set" : "No automatic response set";
      return people+" can reply to this post<br>"+chat+".";
    },
  },
  watch: {
    navigateBack() {
      if(this.navigateBack) {
        if(this.currentNav != null) {
          this.$emit('navigatedBack');
          switch (this.currentNav) {
            /* case 'category-select':
              if(this.isInitialSteps) {
                this.categorySelectModal.dismiss();
                this.root.postComposerModal.dismiss();
                this.$emit('composerClosed');
                this.currentNav = null;
              }
              break; */
            case 'create-post-description':
              if (this.isInitialSteps) {
                this.enterAnimation = animations.enterFromLeft;
                this.postDescriptionCreateModal.dismiss();
                //this.openCategorySelect();
                this.$emit('composerClosed');
              } else {
                this.postDescriptionCreateModal.dismiss();
                this.currentNav = null;
              }
              break;
            case 'reco-tag-select':
              if (this.isInitialSteps) {
                this.enterAnimation = animations.enterFromLeft;
                this.tagSelectModal.dismiss();
                this.openCreatePostDescription('motto');
              } else {
                this.tagSelectModal.dismiss();
                this.currentNav = null;
              }
              break;
            case 'post-preview':
              if (this.isInitialSteps) {
                this.enterAnimation = animations.enterFromLeft;
                this.postPreviewModal.dismiss();
                this.openRecoTagSelect();
              } else {
                this.postPreviewModal.dismiss();
                this.currentNav = null;
              }
              break;
            case 'image-editor':
              if (this.isInitialSteps) {
                this.enterAnimation = animations.enterFromLeft;
                this.imageEditorModal.dismiss();
                this.openRecoTagSelect();
              } else {
                this.imageEditorModal.dismiss();
                this.currentNav = null;
              }
              break;
          
            default:
              break;
          }
        }
      }
    }
  },
  async mounted() {
    this.openCreatePostDescription('motto');
    const postImageFiles = this.post && this.post.images ? await this.fetchPostImages() : [];
    this.images =  postImageFiles;
  },
  methods: {

    // select category
    /* openCategorySelect() {
      this.currentNav = 'category-select';
      return modalbuilders.buildCategorySelect(this, {
          enterAnimation: this.getEnterAnimation(),
          leaveAnimation: animations.defaultLeave,
        }, {
          backButtonClicked: !this.isInitialSteps ? false : () => {
            this.categorySelectModal.dismiss();
            this.root.postComposerModal.dismiss();
          },
          doneButtonClicked: !this.category ? false : () => {
            if (this.isInitialSteps) {
              this.enterAnimation = animations.enterFromRight;
              this.categorySelectModal.dismiss();
              this.openCreatePostDescription('motto');
            } else {
              this.leaveAnimation = animations.defaultLeave;
              this.categorySelectModal.dismiss();
            }
          },
      });
    }, */

    // create description
    openCreatePostDescription(triggeredBy) {
      this.currentNav = 'create-post-description';
      return modalbuilders.buildCreatePostDescription(this, {
          enterAnimation: this.getEnterAnimation(),
          leaveAnimation: animations.defaultLeave,
        }, {
          backButtonClicked: () => {
            this.postDescriptionCreateModal.dismiss();
            this.$emit('composerClosed');
          },
          doneButtonClicked: () => {
            if (this.isInitialSteps) {
              this.enterAnimation = animations.enterFromRight;
              this.postDescriptionCreateModal.dismiss();
              this.openRecoTagSelect();
            } else {
              this.leaveAnimation = animations.defaultLeave;
              this.postDescriptionCreateModal.dismiss();
            }
          },
          activeFeatures: this.activeFeatures,
          postLanguageChanged: (lang) => { this.onPostLanguageChanged(lang) } 
      }, triggeredBy);
    },

    // select tags
    openRecoTagSelect() {
      this.currentNav = 'reco-tag-select';
      return modalbuilders.buildTagSelect(this, {
          enterAnimation: this.getEnterAnimation(),
          leaveAnimation: animations.defaultLeave,
        }, {
          backButtonClicked: () => {
            if (this.isInitialSteps) {
              this.enterAnimation = animations.enterFromLeft;
              this.tagSelectModal.dismiss();
              this.openCreatePostDescription('motto');
            } else {
              this.tagSelectModal.dismiss();
            }
          },
          doneButtonClicked: () => {
            if (this.isInitialSteps) {
              this.enterAnimation = animations.enterFromRight;
              this.tagSelectModal.dismiss();
              this.openPostPreview();
            } else {
              this.tagSelectModal.dismiss();
            }
          },
      },this.excludedFeatures, false, this.tags, this.language);
    },

    // select response type
    openPostPreview() {
      console.log('post preview open');
      this.currentNav = 'post-preview';
      return modalbuilders.buildPostPreview(this, {
          enterAnimation: this.getEnterAnimation(),
          leaveAnimation: animations.defaultLeave,
        }, {
          backButtonClicked: () => {
            if (this.isInitialSteps) {
              this.enterAnimation = animations.enterFromLeft;
              this.postPreviewModal.dismiss();
              this.openRecoTagSelect();
            } else {
              this.postPreviewModal.dismiss();
            }
          },
          doneButtonClicked: () => {
            this.onSubmit();
            this.postPreviewModal.dismiss();
          },
          previewCloseButtonClicked: () => {
            this.$emit('composerClosed');
          }
      });
    },

    // create image editor
    openImageEditor() {
      this.currentNav = 'image-editor';
      return modalbuilders.buildImageEditor(this, {
          enterAnimation: this.getEnterAnimation(),
          leaveAnimation: animations.defaultLeave,
        }, {
          backButtonClicked: () => {
            if (this.isInitialSteps) {
              this.enterAnimation = animations.enterFromLeft;
              this.imageEditorModal.dismiss();
              this.openRecoTagSelect();
            } else {
              this.imageEditorModal.dismiss();
            }
          },
          doneButtonClicked: () => {
            if (this.isInitialSteps) {
              this.enterAnimation = animations.defaultEnter;
              this.imageEditorModal.dismiss();
            } else {
              this.imageEditorModal.dismiss();
            }
            this.isInitialSteps = false;
            this.isNextButton = false;
          },
      });
    },

    // select audience
    openAudienceSelect() {
      return modalbuilders.buildAudienceSelect(this);
    },

    // select expiration
    openExpirationSelect() {
      return modalbuilders.buildExpirationSelect(this);
    },

    // select distance
    openLocationSelect() {
      return modalbuilders.buildLocationSelect(this); 
    },

    // select response type
    openResponseTypeSelect() {
      return modalbuilders.buildResponseTypeSelect(this);  
    },

    // create tag value from input
    getTagValue(input) {
      input = input.replace(/\s\s+/g, ' ').trim();
      const words = input.split(" ");
      let lowerCaseWords = [];
      for (let i = 0; i < words.length; i++) {
        lowerCaseWords.push(words[i].toLowerCase());
      }
      return lowerCaseWords.join("_");
    },

    getEnterAnimation() {
      return this.enterAnimation;
    },

    getLeaveAnimation() {
      return this.leaveAnimation;
    },

    // submit post
    onSubmit() {
      this.submitPost(this.getPost('post'));
    },

    // return post object
    getPost(type) {
      const comp = this;
      let post = {
        settings: {
          type: this.type,
          gender: this.gender,
          age: this.age,
          expiration: this.expiration,
          distance: this.distance,
          max_responses: this.maxResponses === 13 ? 10000000 : this.maxResponses,
          chat_type: this.chatType,
          automatic_response: this.automaticResponse,
        },
        attributes: {
          gender: this.me.gender,
          birthday: this.me.birthday,
          tags: this.parseTagsForAttributes(this.tags),
          category: this.category,
          is_replied: false,
          language: this.language,
          bookmarked: this.post && this.post.bookmarked ? this.post.bookmarked : [],
          replies: []
        },
        display: {
          user: { 
            uid: this.me.uid, 
            nickname: this.me.nickname, 
            avatar: this.me.avatar,
          },
          type: this.type,
          activity_date_time: this.activityDateTime,
          category: this.category,
          images: type == 'preview' ? this.imageURLs : this.images,
          image_dimensions: this.imageDimensions,
          tags: this.parseTagsForDisplay(this.tags),
          subject: this.motto,
          description: this.description,
          timestamp: Date.now(),
        },
        _meta: {
          location: this.devLocation.value != "none" ? this.devLocation.location : this.me.location,
          tags: this.tags,
          editId: comp.post && comp.post.id ? comp.post.id : null
        },
        timestamp: Date.now()
      }
      if (type == 'preview') {
        post.display.distance = 0;
      }
      post.settings.expiration.expires_at = (moment().unix() + post.settings.expiration.seconds) * 1000;
      post.settings.expiration.is_expired = false;
      return post;
    },

    parseTagsForDisplay(oldTags) {
      let tags = [];
      for (var i = 0; i < oldTags.length; i++) {
        tags.push({
          value: oldTags[i].value,
          display_name: oldTags[i].display_name,
          is_recommended: oldTags[i].is_recommended,
          matching: false
        })
      }
      return tags;
    },

    parseTagsForAttributes(oldTags) {
      let tags = {};
      for (var i = 0; i < oldTags.length; i++) {
        tags[oldTags[i].value] = {
          value: oldTags[i].value,
          display_name: oldTags[i].display_name,
          matching: false
        }
      }
      return tags;
    },
    async fetchPostImages(){
      const images = this.post.images.map( async (url, idx) =>{        
        const fileName = 'downloaded' + idx + '.jpg'
        const response = await fetch(url);          
        const contentType = response.headers.get('content-type');
        const blob = await response.blob();
        return new File([blob], fileName, { contentType });         
      });      
      const result = await Promise.all(images);
      return result;
    },
    onPostLanguageChanged(lang){
      this.postLanguageChanged(lang);
    }
  }
}
</script>

<style scoped lang="css">
  .loc-item {
    --border-color: rgba(0,0,0,0.2);
  }
  .loc-row {
    padding: 4px 0;
  }
  .loc-row-one-line {
    padding: 9px 0;
  }
  .loc-row-with-input {
    padding: 2px 0;
  }
  .loc-col {
    padding: 3px;
  }
  .placeholder {
    font-size: 16px;
    color: var(--reco-lighter-font-color);
  }
  .value {
    font-size: 16px;
    font-weight: 600;
  }
  .placeholder .secondary,
  .value .secondary {
    font-size: 13px;
    color: var(--reco-lighter-font-color);
  }
  .icon-container {
    display: inline-block;
    width: 36px;
    line-height: 36px;
    text-align: center;
    border-radius: 18px;
    color: #fff;
    background: red;
  }
  .icon-container.inline {
    margin: 10px 15px 10px 0;
  }
  .right-arrow {
    font-size: 26px;
    color: var(--reco-lighter-font-color);
  }
  .motto-input {
    width: 100%;
    line-height: 24px;
    font-size: 16px;
  }
  .description-input {
    width: 100%;
    line-height: 18px;
    resize: none;
    font-size: 16px;
  }
  .advanced-settings-button {
    font-size: 16px;
    color: var(--ion-color-primary);
  }
  .settings-grid {
    font-size: 14px;
  }
  .section-title {
    font-size: 16px;
    text-transform: uppercase;
    padding: 14px 0 10px 0;
  }
  .section-title.last {
    padding: 9px 0 10px 0;
  }
  .section-ul {
    padding-left: 20px;
    line-height: 26px;
    margin-top: 5px;
    width: 100%;
  }
  .edit-icon {
    position: relative;
    top: 1px;
    display: inline-block;
    margin-left: 3px;
    float: right;
  }
</style>