import {
  IndexGenerator as Base,
  ReExports,
  reExportsAllSymbols,
} from '@stylable/cli';

import wufComponents from '../../../../.wuf/components.json';

const components = {
  ...wufComponents,
  BaseCalendar: { path: 'src/Calendar/BaseCalendar' },
};

type ComponentList = keyof typeof components;

const themingEntries = ['src/colors.st.css'];

export class Generator extends Base {
  public generateReExports(filePath: string): ReExports | undefined {
    for (const entry of themingEntries) {
      if (filePath.includes(entry)) {
        return reExportsAllSymbols(filePath, this);
      }
    }

    const extractedFileName = filePath
      .match(/[ \w-]+\.st.css/)?.[0]
      .replace('.st.css', '');

    if (!extractedFileName || !(extractedFileName in components)) {
      return;
    }

    const envFolder = /\/dist\/es\//.test(filePath) ? 'es/src/' : 'src/';

    const componentRelativePath = components[
      extractedFileName as ComponentList
    ].path.replace('src/', envFolder);

    const componentFullPath = `${
      filePath.split(envFolder)[0]
    }${componentRelativePath}/${extractedFileName}.st.css`;

    // ignore all other stylable files that are not directly positioned next to the component
    if (componentFullPath !== filePath) {
      return;
    }

    return reExportsAllSymbols(filePath, this);
  }
  protected generateIndexSource() {
    const source = super.generateIndexSource();
    return '@st-namespace "INDEX";\n' + source;
  }
}
