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

function patchNativeScriptApplication(androidProjectFolder) {
  try {
    const nsPackage = path.join(
      androidProjectFolder,
      'app',
      'src',
      'main',
      'java',
      'com',
      'tns'
    );
    if (!fs.existsSync(nsPackage)) {
      console.log('Android not installed, skipping Norrix OTA hook.');
      return;
    }

    // patch NativeScriptApplication so NorrixOTA.activatePackage it's only called once in the app lifecycle
    const nsAppFile = path.join(nsPackage, 'NativeScriptApplication.java');
    replaceInFile(
      nsAppFile,
      'super.onCreate();',
      // adding a space so we don't do this more than once
      'super.onCreate() ;\n\t\t\t\tNorrixOTA.activatePackage(this);'
    );
  } catch (e) {
    console.log('Norrix OTA Android hook error: ' + e);
  }
}

function replaceInFile(someFile, what, by) {
  fs.readFile(someFile, 'utf8', function (err, data) {
    if (err) {
      return console.log(err);
    }
    const result = data.replace(what, by);

    fs.writeFile(someFile, result, 'utf8', function (err) {
      if (err) return console.log(err);
    });
  });
}

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

  if (platform === 'android') {
    const androidProjectFolder = getNativeProjectDir(
      $injector,
      platform,
      hookArgs
    );
    patchNativeScriptApplication(androidProjectFolder);
  }
}
