import Vue from 'vue';
import Vuex from 'vuex';

import { get } from '../helpers/api.js';

Vue.use(Vuex);

const storeTest = {
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  }
};

const mainActions = {
  state: {
    saving: false,
    discarding: false,
    addingNew: false,
    showingDelete: false,
    deleting: false
  },
  mutations: {
    initiateSave(state) {
      state.saving = true;
    },
    concludeSave(state) {
      state.saving = false;
    },
    initiateDiscard(state) {
      state.discarding = true;
    },
    concludeDiscard(state) {
      state.discarding = false;
    },
    initiateAddNew(state) {
      state.addingNew = true;
    },
    concludeAddNew(state) {
      state.addingNew = false;
    },
    showDelete(state) {
      state.showingDelete = true;
    },
    hideDelete(state) {
      state.showingDelete = false;
    },
    initiateDelete(state) {
      state.deleting = true;
    },
    concludeDelete(state) {
      state.deleting = false;
    }
  }
};

const mainVariables = {
  state: {
    statusMask: 8,
    pagePassword: null
  },
  mutations: {
    setStatus(state, mask) {
      state.statusMask = mask;
    },
    resetStatus(state) {
      // Resetting to default status
      state.statusMask = 8;
    },
    setPagePassword(state, password) {
      state.pagePassword = password;
    },
    resetPagePassword(state) {
      state.pagePassword = null;
    }
  }
};

const mainStorage = {
  state: {
    whoami: null,
    files: null
  },
  mutations: {
    getFiles(state) {
      get('buildable_files', window.jwtToken)
        .then( (res) => {
          if (!!res && !!res.data && !!res.data.files) {
            state.files = res.data.files.map( function(file) {
              if (!!file.mime_type) {
                file.type = file.mime_type.substring(0, file.mime_type.indexOf('/'));
              }
              file.selected = false;
              return file;
            });
          }
        })
        .catch( (err) => {
          console.log(err);
        });
    },
    setFiles(state, files) {
      state.files = files;
    },
    resetFiles(state) {
      state.files = null;
    },
    setWhoami(state, whoami) {
      state.whoami = whoami;
    },
    resetWhoami(state) {
      state.whoami = null;
    }
  }
};

export default new Vuex.Store({
  modules: {
    test: storeTest,
    actions: mainActions,
    variables: mainVariables,
    storage: mainStorage
  }
})
