import { $$, forEach } from "@acanto/core-dom";

/**
 * Swap route style
 * 
 * @param {import("@barba/core/dist/core/src/defs/transition").ITransitionData} data Barba hook data
 */
function swapRoutesStyle(data) {
  const nextId = data.next.namespace;
  if (__DEV__) {
    console.info("routesBarba: swapRoutesStyle, next id is:" + nextId);
  }

  // enable only the next route's style tag
  forEach($$("[data-route-style]"), $style => {
    if ($style.getAttribute("data-route-style") === nextId) {
      if (__DEV__) console.info("routesBarba: enabling style for" + nextId);
      $style.removeAttribute("type");
    } else {
      if (__DEV__) console.info("routesBarba: disabling style for" + $style.id);
      $style.setAttribute("type", "text");
    }
  });
}

/**
 * Routes definitions for barba-js
 */
export default function routesBarba() {
  const instances = {};

  function getInstanceSafely(id, module) {
    if (!instances[id]) {
      // class based routes:
      // instances[id] = new module.default({ id });
      // function based routes:
      instances[id] = module.default({ id });
    }
    return instances[id];
  }

  return [<% routes.forEach(route => { %>{
      namespace: "<%= route %>",
      beforeEnter(data) {
        if (__DEV__) {
          console.log("routesBarba: <%= route %>->beforeEnter", data);
        }
        import("routes/<%= route %>").then((module) => {
          getInstanceSafely("<%= route %>", module);
        });
        
        swapRoutesStyle(data);
      },
      afterEnter(data) {
        if (__DEV__) {
          console.log("routesBarba: <%= route %>->afterEnter", data);
          // import scss too during dev as we are using style-loader...
          import("routes/<%= route %>/index.scss");
        }
        import("routes/<%= route %>").then((module) => {
          getInstanceSafely("<%= route %>", module).__m(data);
        });
      },
      afterLeave(data) {
        if (__DEV__) {
          console.log("routesBarba: <%= route %>->afterLeave", data);
        }
        import("routes/<%= route %>").then((module) => {
          getInstanceSafely("<%= route %>", module).__d(data)
        });
      }
    },<% }) %>  
  ];
}
