<template>
  <div id="customization_view" class="view customization-view">
    <div class="view-title">
      <h1>Customization</h1>
    </div>
    <div class="view-content">
      <div class="tabbed-content">
        <div class="tabs">
          <a class="tab" :class="{ active : (currentTab === tab) }" @click="changeTab(tab)" v-for="tab in tabs">
            {{ tab }}
          </a>
        </div>
        <div class="tab-view">
          <component :is="currentTabComponent" v-bind.sync="currentProperties" @update="updateProperties"></component>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { get } from '../helpers/api.js';
  import { put } from '../helpers/api.js';
  
  export default {
    data() {
      return {
        currentTab: this.$route.params['tab'] || "Colors",
        tabs: [ "Colors", "Fonts", "Header", "Footer", "Posts", "Menus" ],
        somethingChanged: false,
        properties: {
          "Colors": {
            primarySecondaryColors: [],
            tertiaryQuaternaryQuinaryColors: []
          },
          "Fonts": {
            fontSizeMultiplier: null,
            headerFontFamily: null,
            bodyFontFamily: null
          },
          "Header": {
            headerLogo: null,
            headerText: null,
            headerOptions: null,
            headerHeight: null,
            headerColor: null,
            headerLinkColor: null,
            headerButtonColor: null,
            headerSubNavColor: null,
            headerSubNavLinkColor: null
          },
          "Footer": {
            footerLogo: null,
            footerText: null,
            footerLogoLink: null,
            footerHeight: null,
            footerColor: null,
            subFooterColor: null,
            copyrightText: null,
            footerLink1: null,
            footerLink2: null
          },
          "Posts": {
            postsTitle: null,
            postsDescription: null,
            postsPlaceholderImages: null
          },
          "Menus": {
            header: { type: "header", content: null, metas: [] },
            footer: { type: "footer", content: null, metas: [] },
            mobile: { type: "mobile", content: null, metas: [] },
            secondaries: [],
            deletedMenus: []
          }
        },
        typeMask: 1
      };
    },
    created() {
      this.initData();
    },
    computed: {
      currentTabComponent: function() {
        return 'custom-' + this.currentTab.toLowerCase();
      },
      currentProperties: function() {
        return this.properties[this.currentTab];
      },
      isSaving: function() {
        return this.$store.state.actions.saving;
      },
      isDiscarding: function() {
        return this.$store.state.actions.discarding;
      }
    },
    watch: {
      isSaving: function(isSaving) {
        if (!!isSaving) {
          this.submit();
        }
      },
      isDiscarding: function(isDiscarding) {
        if (!!isDiscarding) {
          window.location.reload(true);
        }
      }
    },
    methods: {
      initData() {
        const self = this;
        
        get('buildable_settings/?type_mask=' + this.typeMask, window.jwtToken)
          .then( (res) => {
            if (!!res && !!res.data && !!res.data.settings) {
              this.assignProperties(res.data.settings);
            }
          })
          .catch( (err) => {
            console.log(err);
          });
        
        get('buildable_menus', window.jwtToken)
          .then( (res) => {
            if (!!res && !!res.data && !!res.data.menus) {
              res.data.menus.forEach( function(menu) {
                menu.removed_pages = [];
                if (menu.type !== "inner_nav") {
                  self.properties["Menus"][menu.type] = menu;
                }
                else {
                  self.properties["Menus"].secondaries.push(menu);
                }
              });
            }
          })
          .catch( (err) => {
            console.log(err);
          });

        this.$store.commit('getFiles');
      },
      assignProperties(settings) {
        const self = this;
        settings.forEach( function(setting) {
          if (setting.slug.indexOf("color") > -1
          && setting.slug.indexOf("header") === -1
          && setting.slug.indexOf("footer") === -1) {
            let subsetName = "tertiaryQuaternaryQuinaryColors"
            if (setting.slug.indexOf("primary") > -1 || setting.slug.indexOf("secondary") > -1) {
              subsetName = "primarySecondaryColors";
            }
            self.properties["Colors"][subsetName].push({
              title: setting.name,
              name: setting.name.substring(0, setting.name.indexOf(" ")),
              slug: setting.slug,
              color: { hex: setting.value }
            });
          }
          else {
            let category = undefined;
            let propName = setting.slug.replace(/-([a-z0-9])/g, function (g) {
              return g[1].toUpperCase();
            });

            if (setting.slug.indexOf("font") > -1) {
              category = "Fonts";
            }
            else if (setting.slug.indexOf("header") > -1) {
              category = "Header"
            }
            else if (setting.slug.indexOf("footer") > -1 || setting.slug.indexOf("copyright") > -1) {
              category = "Footer";
            }
            else {
              category = "Posts";
            }
            
            self.properties[category][propName] = {
              type_mask: self.typeMask,
              name: setting.name,
              slug: setting.slug,
              value: setting.value
            };
          }
        });
      },
      changeTab(tab) {
        this.currentTab = tab;
        this.$router.push('/customization/' + tab)
      },
      updateProperties(data) {
        console.log("something changed?!");
        this.somethingChanged = true;
        if (data.category === "Colors") {
          // this.properties[data.category][data.prop] = data.value;
        }
        else {
          this.properties[data.category][data.prop].value = data.value;
        }
      },
      submit() {
        console.log("Saving.......");
        const settings = [];
        
        // Add settings to settings_form_params
        for (let propertyCategory in this.properties) {
          if (propertyCategory === "Colors") {
            for (let colorGroup in this.properties[propertyCategory]) {
              this.properties[propertyCategory][colorGroup].forEach( function(color) {
                settings.push({ type_mask: 1, name: color.title, slug: color.slug, value: color.color.hex });
              });
            }
          }
          else if (propertyCategory !== "Menus") {
            for (let setting in this.properties[propertyCategory]) {
              settings.push(this.properties[propertyCategory][setting]);
            }
          }
        }
        
        const settings_form_params = {
          settings: settings,
          type_mask: this.typeMask
        };
        
        const menus_form_params = { menus: [] };
        for (let menuType in this.properties["Menus"]) {
          if (menuType === "secondaries") {
            this.properties["Menus"][menuType].forEach( function(secondaryMenu) {
              menus_form_params.menus.push(secondaryMenu);
            })
          }
          else if (menuType === "deletedMenus") {
            menus_form_params.deleted_menus = this.properties["Menus"][menuType];
          }
          else {
            menus_form_params.menus.push(this.properties["Menus"][menuType]);
          }
        }
        
        put('buildable_settings', settings_form_params, window.jwtToken)
          .then( (res) => {
            console.log(res);
            this.somethingChanged = false;
          })
          .catch( (err) => {
            console.log(err);
          });
        
        put('buildable_menus', menus_form_params, window.jwtToken)
          .then( (res) => {
            console.log(res);
            this.somethingChanged = false;
          })
          .catch( (err) => {
            console.log(err);
          });
        
        this.$store.commit("concludeSave");
      }
    },
    beforeRouteLeave(to, from, next) {
      console.log("beforeRouteLeave, going to view: " + to.meta.view + "\n!!this.somethingChanged is " + !!this.somethingChanged);
      if (to.meta.view !== "Customization" && !!this.somethingChanged && !confirm('You have unsaved changes. You sure?')) {
        next(false);
      }
      else {
        next();
      }
    }
  }
</script>
