import FipamoAdminAPI, { TASK_SYNC_NAV } from "../../libraries/FipamoAdminAPI";
import NavActions from "../actions/NavActions";
import * as DataEvent from "../events/DataEvent";
import Notifications from "../ui/Notifications";
import Sortable from "sortablejs";
const notify = new Notifications();

export default class NavIndex {
  //--------------------------
  // constructor
  //--------------------------
  constructor() {
    this.processing = false;
    this.admin = new FipamoAdminAPI(null);
    this.start();
  }
  //--------------------------
  // methods
  //--------------------------
  start() {
    let self = this;
    Sortable.create(document.getElementById("nav-pages"), {
      onUpdate: () => {
        new NavActions().syncMenu().then((data) => {
          notify.alert("Updating Menu", null);
          self.admin.sync(TASK_SYNC_NAV, data).then((r) => {
            if (r.type == DataEvent.MENU_UPDATED) {
              notify.alert(r.message, true);
            } else {
              notify.alert(r.message, true);
            }
          });
        });
      }
    });
    var nav = document.querySelectorAll(".nav-btn");
    for (var i = 0, length = nav.length; i < length; i++) {
      nav[i].addEventListener("click", (e) => this.handleNavButton(e), false);
    }
  }
  //--------------------------
  // event handlers
  //--------------------------
  handleNavButton(e) {
    if (this.processing) return;
    let id = "";
    let self = this;
    switch (e.target.id) {
      case "remove-item":
        id = e.target.getAttribute("data-id");
        new NavActions().removeItem(id);
        new NavActions().syncMenu().then((data) => {
          data.remove = e.target.getAttribute("data-uuid");
          notify.alert("Editing Menu", null);
          self.processing = true;
          self.admin.syncNav(data).then((r) => {
            self.processing = false;
            if (r.type == DataEvent.MENU_UPDATED) {
              notify.alert(r.message, true);
            } else {
              notify.alert(r.message, true);
            }
          });
        });
        break;
      case "edit-item":
        self.processing = false;
        window.location =
          "/dashboard/page/edit/" + e.target.getAttribute("data-id");
        break;
    }
  }
}
