import fs from 'fs';
import path from 'path';
import {
  getPlatformFromPrepareHookArgs,
  getNativeProjectDir,
} from '../helper.mjs';

function patchUIApplicationMain(iosProjectFolder, platform) {
  try {
    const nsInteralFolder = path.join(iosProjectFolder, 'internal');
    if (!fs.existsSync(nsInteralFolder)) {
      console.log(`${platform} not installed, skipping Norrix OTA hook.`);
      return;
    }

    const bootFileName =
      platform === 'visionos' ? 'NativeScriptStart.m' : 'main.m';
    const bootFilePath = path.join(nsInteralFolder, bootFileName);
    let bootFileContents = fs.readFileSync(bootFilePath, 'utf8');

    // include NorrixOTA sdk if needed
    if (bootFileContents.indexOf('NorrixOTA') === -1) {
      bootFileContents = replaceInContents(bootFileContents, {
        '#import <NativeScript/NativeScript.h>':
          '#import <NativeScript/NativeScript.h>\n#import <NorrixOTA/NorrixOTA.h>',
        'config.BaseDir = baseDir;':
          'config.BaseDir = [NorrixOTA applicationPathWithDefault:[[NSBundle mainBundle] resourcePath]];',
      });

      fs.writeFileSync(bootFilePath, bootFileContents, 'utf8');
    }
  } catch (e) {
    console.log('Norrix OTA iOS hook error: ' + e);
  }
}

function replaceInContents(startingContents, replacements) {
  let contents = startingContents;
  for (const key in replacements) {
    const what = key;
    const by = replacements[key];
    contents = contents.replace(what, by);
  }
  return contents;
}

export default function ($injector, hookArgs) {
  const platform = getPlatformFromPrepareHookArgs(hookArgs);

  if (platform === 'ios' || platform === 'visionos') {
    const iosProjectFolder = getNativeProjectDir($injector, platform, hookArgs);
    patchUIApplicationMain(iosProjectFolder, platform);
  }
}
