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