<template>
  <div id="pages_view" class="view pages-view">
    <div class="view-title">
      <h1>Pages</h1>
    </div>
    <div class="view-content">
      <div class="top" v-if="!!pages && pages.length > 0">
        <filter-dropdown class="dark" :options="filterOptions" option-label="name" option-key="mask" v-model="selectedFilters" />
      </div>
      <div class="table-container" v-if="!!pages && pages.length > 0">
        <table border="1" cellspacing="0">
          <thead>
            <tr>
              <th><input type="checkbox" v-model="selectAll" /></th>
              <th></th>
              <th class="page_name-column sorter" @click="sort('title')">
                <span class="name">Page Name</span>
                <span class="icon-container" v-if="currentSort === 'title'">
                  <i class="fas" :class="{ 'fa-sort-up': currentSortDir === 'asc', 'fa-sort-down': currentSortDir === 'desc' }"></i>
                </span>
              </th>
              <th class="status-column sorter" @click="sort('status_mask')">
                <span class="name">Status</span>
                <span class="icon-container" v-if="currentSort === 'status_mask'">
                  <i class="fas" :class="{ 'fa-sort-up': currentSortDir === 'asc', 'fa-sort-down': currentSortDir === 'desc' }"></i>
                </span>
              </th>
              <th class="user-column sorter" @click="sort('user')">
                <span class="name">User</span>
                <span class="icon-container" v-if="currentSort === 'user'">
                  <i class="fas" :class="{ 'fa-sort-up': currentSortDir === 'asc', 'fa-sort-down': currentSortDir === 'desc' }"></i>
                </span>
              </th>
              <th class="updated-column sorter" @click="sort('updated_at')">
                <span class="name">Updated</span>
                <span class="icon-container" v-if="currentSort === 'updated_at'">
                  <i class="fas" :class="{ 'fa-sort-up': currentSortDir === 'asc', 'fa-sort-down': currentSortDir === 'desc' }"></i>
                </span>
              </th>
            </tr>
          </thead>
          <tbody>
            <tr :class="{ checked: selected.indexOf(page.id) > -1 }" @click="check(page.id)" v-for="(page, index) in pages">
              <td><input type="checkbox" v-model="selected" :value="page.id" number /></td>
              <td>
                <i class="fas fa-home fa-fw" v-if="page.is_homepage === 1"></i>
                <i class="far fa-lock-alt fa-fw" v-if="!!page.active_user_id && page.active_user_id !== currentUser.id"></i>
              </td>
              <td><a class="no-hover" @click="edit(page.slug, page.active_user_id)">{{ page.title }}</a></td>
              <td class="hover-only" colspan="3">
                <a class="no-hover" @click="view(page.slug)">view</a>
                <span>|</span>
                <a class="no-hover" @click="edit(page.slug, page.active_user_id)" v-if="!page.active_user_id || (!!page.active_user_id && page.active_user_id === currentUser.id)">edit</a>
                <span v-if="!page.active_user_id || (!!page.active_user_id && page.active_user_id === currentUser.id)">|</span>
                <a class="no-hover" @click="setHome(page.slug, index)">set as home page</a>
                <span v-if="!page.active_user_id || (!!page.active_user_id && page.active_user_id === currentUser.id)">|</span>
                <a class="no-hover" @click="deletePage(page.slug)" v-if="!page.active_user_id || (!!page.active_user_id && page.active_user_id === currentUser.id)">delete</a>
                <a class="no-hover" v-if="isBeingEdited(page) && currentUser.id !== page.active_user.id"> | {{page.active_user.first_name}} {{page.active_user.last_name}} is editing this page.</a>
              </td>
              <td class="hide-on-hover">{{ getStatus(page.status_mask) }}</td>
              <td class="hide-on-hover"><span v-if="!!page.user">{{ page.user.first_name }} {{ page.user.last_name }}</span></td>
              <td class="hide-on-hover">{{ formatDateTime(page.updated_at) }}</td>
            </tr>
          </tbody>
        </table>
        <div class="pagination-container" v-if="data.length > pageSize">
          <a class="icon-container previous" @click="prevPage" v-if="currentPage > 1">
            <i class="far fa-angle-left"></i>
          </a>
          <span class="current-page">{{ currentPage }}</span>
          <a class="icon-container next" @click="nextPage" v-if="(currentPage * pageSize) < data.length">
            <i class="far fa-angle-right"></i>
          </a>
        </div>
      </div>
      <div class="empty-state" v-else-if="!pages || (!!pages && pages.length === 0)">
        <div class="icon-container"><i class="far fa-exclamation-circle"></i></div>
        <div class="text">
          You don't have any pages yet.<br />Create a page by clicking the button below.
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { get, put } from '../helpers/api.js';

  export default {
    data() {
      return {
        data: [],
        currentUser: this.$store.state.storage.whoami,
        currentSort: 'title',
        currentSortDir: 'asc',
        pageSize: 20,
        currentPage: 1,
        selected: [],
        selectedFilters: [ 8, 1, 2, 4 ],
        filterOptions: [
          { name: "Draft", mask: 8 },
          { name: "Public", mask: 1 },
          { name: "Private", mask: 2 },
          { name: "Password Protected", mask: 4 },
          { name: "Deleted", mask: 128 }
        ]
      };
    },
    mounted() {
      this.initData();
    },
    computed: {
      pages: function() {
        const self = this;
        return this.data.sort( function(a, b) {
          let modifier = (self.currentSortDir === 'asc') ? 1 : -1;
          let aValue, bValue;

          if (self.currentSort === 'title') {
            aValue = a[self.currentSort];
            bValue = b[self.currentSort];
          }
          else if (self.currentSort === 'status_mask') {
            aValue = self.getStatus(a[self.currentSort]);
            bValue = self.getStatus(b[self.currentSort]);
          }
          else if (self.currentSort === 'updated_at') {
            aValue = self.$moment(a[self.currentSort]).unix();
            bValue = self.$moment(b[self.currentSort]).unix();
          }

          if (!!aValue && !!bValue) {
            if (aValue < bValue) {
              return -1 * modifier;
            }
            else if (aValue > bValue) {
              return 1 * modifier;
            }
          }

          return 0;
        }).filter( function(row, index) {
          let start = (self.currentPage - 1) * self.pageSize;
          let end = self.currentPage * self.pageSize;

          if (self.selectedFilters.indexOf(row.status_mask) > -1 && index >= start && index < end) {
            return true;
          }
        });
      },
      selectAll: {
        get() {
          return (!!this.data) ? this.data.length === this.selected.length : false;
        },
        set(value) {
          const selected = [];

          if (!!value) {
            this.data.forEach( function(page) {
              selected.push(page.id);
            });
          }

          this.selected = selected;
        }
      },
      selectedLength: function() {
        return this.selected.length;
      },
      isAddingNew: function() {
        return this.$store.state.actions.addingNew;
      },
      isDeleting: function() {
        return this.$store.state.actions.deleting;
      }
    },
    watch: {
      selectedLength: function(val) {
        if (val > 0) {
          this.$store.commit('showDelete')
        }
        else if (val === 0) {
          this.$store.commit('hideDelete')
        }
      },
      isAddingNew: function(isAddingNew) {
        if (!!isAddingNew) {
          console.log("Adding new......");
          this.$router.push("/pages/new");
        }
      },
      isDeleting: function(isDeleting) {
        if (!!isDeleting) {
          console.log("Deleting......");
        }
      }
    },
    methods: {
      initData() {
        get('buildable_pages', window.jwtToken)
          .then( (res) => {
            if (!!res && !!res.data && !!res.data.pages) {
              this.data = res.data.pages.map( function(page) {
                page.checked = false;
                return page;
              });
            }
          })
          .catch( (err) => {
            console.log(err);
          });
      },
      getStatus(mask) {
        if (mask & 1) {
          return "Public";
        }
        else if (mask & 2) {
          return "Private";
        }
        else if (mask & 4) {
          return "Password Protected";
        }
        else if (mask & 8) {
          return "Draft";
        }
        else if (mask & 128) {
          return "Deleted";
        }
      },
      formatDateTime(string) {
        return this.$moment.utc(string).local().format('L');
      },
      sort(key) {
        if (key === this.currentSort) {
          this.currentSortDir = (this.currentSortDir === 'asc') ? 'desc' : 'asc';
        }
        this.currentSort = key;
      },
      check(id) {
        if (this.selected.indexOf(id) > -1) {
          this.selected = this.selected.filter( function(pId) {
            return pId !== id;
          })
        }
        else {
          this.selected.push(id);
        }
      },
      nextPage() {
        if ((this.currentPage * this.pageSize) < this.data.length) {
          this.currentPage++;
        }
      },
      prevPage() {
        if (this.currentPage > 1) {
          this.currentPage--;
        }
      },
      view(slug) {

      },
      edit(slug, activeUserId = null) {
        if (activeUserId == null) {
            this.$router.push("/pages/" + slug);
            return;
        }

        if (activeUserId === this.currentUser.id) {
            this.$router.push("/pages/" + slug);
            return;
        }

        // Otherwise fall through
        // console.log('Page already locked')

      },
      setHome(slug, index) {
        put('buildable_pages/make_homepage/' + slug, null, window.jwtToken)
          .then( (res) => {
            if (!!res && !!res.data && !!res.data.new_homepage) {
              this.pages[index] = res.data.new_homepage;
            }
          })
          .catch( (err) => {
            console.log(err);
          });
      },
      deletePage(slug) {
        const form_params = {
          status_mask: 128
        };

        put('buildable_pages/update_status_mask/' + slug, form_params, window.jwtToken)
          .then( (res) => {
            if (!!res && !!res.data && !!res.data.updated_page) {
              this.initData();
            }
          })
          .catch( (err) => {
            console.log(err);
          });
      },
      isBeingEdited(page) {
        return page.active_user_id != null;
      }
    }
  }
</script>
