/*
 * Copyright (C) 2022 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import glob from 'glob';
import {readFileSync} from 'fs';
import {matchPropertyContent, matchTagProperties} from '../src/app/util/ion-icon/icon-match';

const globPromise = (pattern: string) =>
  new Promise<string[]>((resolve, reject) =>
    glob(pattern, (error, files) => (error ? reject(error) : resolve(files))),
  );

/**
 *
 */
export async function getUsedIconsHtml(glob = 'src/**/*.html'): Promise<Record<string, string[]>> {
  return Object.fromEntries(
    (await globPromise(glob))
      .map(file => [
        file,
        (readFileSync(file, 'utf8')
          .match(matchTagProperties('ion-icon'))
          ?.flatMap(match => {
            return match.match(matchPropertyContent(['name', 'md', 'ios']));
          })
          .filter(it => !!it) as string[]) || [],
      ])
      .filter(([, values]) => values.length > 0),
  );
}

/**
 *
 */
export async function getUsedIconsTS(glob = 'src/**/*.ts'): Promise<Record<string, string[]>> {
  return Object.fromEntries(
    (await globPromise(glob))
      .map(file => [file, readFileSync(file, 'utf8').match(/(?<=Icon`)[\w-]+(?=`)/g) || []])
      .filter(([, values]) => values.length > 0),
  );
}
