import { isPartOfChunk } from './utils/isPartOfChunk';
import { maybeReportChunkSorting } from './utils/maybeReportChunkSorting';
import { maybeReportExportSpecifierSorting } from './utils/maybeReportExportSpecifierSorting';

import { extractChunks } from '../../utils/shared';

const meta = {
  docs: { url: 'https://github.com/lydell/eslint-plugin-simple-import-sort#sort-order' },
  fixable: 'code',
  messages: { sort: 'Run autofix to sort these exports!' },
  schema: [],
  type: 'layout'
};

const Program = (programNode: any, context: any) => {
  const sourceCode = context.getSourceCode();
  for (const chunk of extractChunks(programNode, (node: any, lastNode: any) => isPartOfChunk(node, lastNode, sourceCode))) {
    maybeReportChunkSorting(chunk, context);
  }
};

const ExportNamedDeclaration = (node: any, context: any) => {
  if (node.source == null && node.declaration == null) {
    maybeReportExportSpecifierSorting(node, context);
  }
};

export const exportsRule = {
  meta,
  create: (context: any) => ({
    Program: (programNode: any) => Program(programNode, context),
    ExportNamedDeclaration: (node: any) => ExportNamedDeclaration(node, context)
  })
};
