import { nonexhaustive } from "@likec4/core";
import { isTruthy } from "remeda";
import { ast } from "../../ast.js";
import { logger, logWarnError } from "../../logger.js";
export function GlobalsParser(B) {
  return class GlobalsParser extends B {
    parseGlobals() {
      const { parseResult, c4Globals } = this.doc;
      const isValid = this.isValid;
      const globals = parseResult.value.globals.filter(isValid);
      const elRelPredicates = globals.flatMap((r) => r.predicates.filter(isValid));
      for (const predicate of elRelPredicates) {
        try {
          const globalPredicateId = predicate.name;
          if (!isTruthy(globalPredicateId)) {
            continue;
          }
          if (globalPredicateId in c4Globals.predicates) {
            logger.warn(`Global predicate named "${globalPredicateId}" is already defined`);
            continue;
          }
          this.parseAndStoreGlobalPredicateGroupOrDynamic(predicate, globalPredicateId, c4Globals);
        } catch (e) {
          logWarnError(e);
        }
      }
      const styles = globals.flatMap((r) => r.styles.filter(isValid));
      for (const style of styles) {
        try {
          const globalStyleId = style.id.name;
          if (!isTruthy(globalStyleId)) {
            continue;
          }
          if (globalStyleId in c4Globals.styles) {
            logger.warn(`Global style named "${globalStyleId}" is already defined`);
            continue;
          }
          const styles2 = this.parseGlobalStyleOrGroup(style);
          if (styles2.length > 0) {
            c4Globals.styles[globalStyleId] = styles2;
          }
        } catch (e) {
          logWarnError(e);
        }
      }
    }
    parseAndStoreGlobalPredicateGroupOrDynamic(astRule, id, c4Globals) {
      if (ast.isGlobalPredicateGroup(astRule)) {
        const predicates = this.parseGlobalPredicateGroup(astRule);
        if (predicates.length > 0) {
          c4Globals.predicates[id] = predicates;
        }
        return;
      }
      if (ast.isGlobalDynamicPredicateGroup(astRule)) {
        const predicates = this.parseGlobalDynamicPredicateGroup(astRule);
        if (predicates.length > 0) {
          c4Globals.dynamicPredicates[id] = predicates;
        }
        return;
      }
      nonexhaustive(astRule);
    }
    parseGlobalPredicateGroup(astRule) {
      return astRule.predicates.map((p) => this.parseViewRulePredicate(p));
    }
    parseGlobalDynamicPredicateGroup(astRule) {
      return astRule.predicates.map((p) => this.parseDynamicViewIncludePredicate(p));
    }
    parseGlobalStyleOrGroup(astRule) {
      if (ast.isGlobalStyle(astRule)) {
        return [this.parseViewRuleStyle(astRule)];
      }
      if (ast.isGlobalStyleGroup(astRule)) {
        return astRule.styles.map((s) => this.parseViewRuleStyle(s));
      }
      nonexhaustive(astRule);
    }
  };
}
