import { ConfigPlugin, WarningAggregator } from '@expo/config-plugins';
import { withProjectBuildGradle } from '@expo/config-plugins/build/plugins/android-plugins';
import { mergeContents } from '@expo/config-plugins/build/utils/generateCode';
import { ScanbotConfigPlugin } from './pluginTypes';

export const withAndroidMavenURLs: ConfigPlugin<Pick<ScanbotConfigPlugin, 'mavenURLs'>> = (
  config,
  { mavenURLs }
) => {
  if (mavenURLs) {
    config = withProjectBuildGradle(config, (gradleProps) => {
      try {
        gradleProps.modResults.contents = addMavenRepo(gradleProps.modResults.contents);
      } catch (error: any) {
        WarningAggregator.addWarningAndroid(
          'react-native-scanbot-barcode-scanner-sdk',
          `Could not add maven URL to project build.gradle. Please insert the following\n` +
            'maven { url "https://nexus.scanbot.io/nexus/content/repositories/releases/" }\n' +
            'maven { url "https://nexus.scanbot.io/nexus/content/repositories/snapshots/" }\n' +
            error.message ?? ''
        );
      }

      return gradleProps;
    });
  }

  return config;
};

export const addMavenRepo = (projectBuildGradle: string) => {
  const regex = new RegExp(/(?=allprojects\s*\{\s*\s*repositories\s*)[\s\S]*/, 'gm');
  const allProjectRepositories = projectBuildGradle.match(regex);

  if (allProjectRepositories && allProjectRepositories.length > 0) {
    const merged = mergeContents({
      src: allProjectRepositories[0],
      newSrc:
        '   maven { url "https://nexus.scanbot.io/nexus/content/repositories/releases/" }\n' +
        '   maven { url "https://nexus.scanbot.io/nexus/content/repositories/snapshots/" }',
      tag: `react-native-scanbot-barcode-scanner-sdk`,
      anchor: new RegExp('repositories {', 'gm'),
      offset: 1,
      comment: '//',
    }).contents;

    return projectBuildGradle.replace(regex, merged);
  } else {
    throw new Error('Could not find project repositories');
  }
};
