// @flow strict

const fs = require('fs');
const path = require('path');
const childProcess = require('child_process');

const log = message => console.log(`➤ ${message}`); // eslint-disable-line no-console

// TODO: fetch .env variables from Vault (or maybe just store the .env file itself in the Vault - this is painful)
const vault = {
  AFFILIATE_BOOKINGCOM: 'null',
  AUTH_ANDROID_GOOGLE_CLIENTID: 'null',
  AUTH_IOS_GOOGLE_CLIENTID: 'null',
  AUTH_KIWI_BACKEND: 'null',
  SENTRY_DSN: 'null',
  API_KEY_GOOGLE_MAPS: 'null',
};

const envTemplate = `
###########################################################################
###                                                                     ###
###                DO NOT UPDATE THIS FILE MANUALLY                     ###
###   To update this file please run "./scripts/configureApplication"   ###
###                                                                     ###
###########################################################################

# Affiliate number is used when sending request to the Booking.com.
# They know (thanks to this number) who is making requests and they'll
# provide branded whitelabel.
#
AFFILIATE_BOOKINGCOM=${vault.AFFILIATE_BOOKINGCOM}

# These client IDs are used by Google login.
# See: https://docs.expo.io/versions/latest/sdk/google.html
#
AUTH_ANDROID_GOOGLE_CLIENTID=${vault.AUTH_ANDROID_GOOGLE_CLIENTID}
AUTH_IOS_GOOGLE_CLIENTID=${vault.AUTH_IOS_GOOGLE_CLIENTID}

# Kiwi backend token is necessary to convert client IDs (Google) to our
# internal Kiwi token. This token is used to communicate with our API.
#
AUTH_KIWI_BACKEND=${vault.AUTH_KIWI_BACKEND}

# Sentry is used to log all errors during client runtime so we can act
# accordingly and fix all production issues.
#
SENTRY_DSN=${vault.SENTRY_DSN}

API_KEY_GOOGLE_MAPS=${vault.API_KEY_GOOGLE_MAPS}
`;

log('Setting up ENV variables...');
fs.writeFileSync(path.join(__dirname, '..', '.env'), envTemplate);

// We need to do this patching as react-native-code-push is actually "linked" as part of our native library RNKiwiMobile
// We might be avoiding this patching when linking is extracted from RN core (with new features)
// Keep an eye on https://github.com/react-native-community/react-native-cli
log('Patching react-native-code-push...');
const rnCodePushPackgeJson = JSON.parse(
  fs.readFileSync(
    path.join(
      __dirname,
      '..',
      'node_modules',
      'react-native-code-push',
      'package.json',
    ),
    'utf-8',
  ),
);
delete rnCodePushPackgeJson.rnpm;

fs.writeFileSync(
  path.join(
    __dirname,
    '..',
    'node_modules',
    'react-native-code-push',
    'package.json',
  ),
  JSON.stringify(rnCodePushPackgeJson, null, 2),
);

log('Linking all native dependencies...');
childProcess.execSync('yarn react-native link');

log('Patching intl package');
const intlPackageJson = JSON.parse(
  fs.readFileSync(
    path.join(__dirname, '..', 'node_modules', 'intl', 'package.json'),
    'utf-8',
  ),
);
delete intlPackageJson.browser;

fs.writeFileSync(
  path.join(__dirname, '..', 'node_modules', 'intl', 'package.json'),
  JSON.stringify(intlPackageJson, null, 2),
);

try {
  fs.unlinkSync(path.join(__dirname, '..', 'node_modules', 'intl', '.babelrc'));
} catch (e) {
  // Ignore error - file doesn't exist
}

log('Configuration complete!');

// Needed before 0.22.0 for Android Studio to sync
log('Patching react-native-maps');
const androidManifestReactNativeMaps = fs.readFileSync(
  path.join(
    __dirname,
    '..',
    'node_modules/react-native-maps/lib/android/src/main/AndroidManifest.xml',
  ),
  'utf-8',
);
const newAndroidManifestReactNativeMaps = androidManifestReactNativeMaps.replace(
  '<uses-sdk android:minSdkVersion="16" />',
  '',
);

fs.writeFileSync(
  path.join(
    __dirname,
    '..',
    'node_modules/react-native-maps/lib/android/src/main/AndroidManifest.xml',
  ),
  newAndroidManifestReactNativeMaps,
);

@@ -3312,41 +3312,8 @@
 %0A%7D%0A%0A
-log('Configuration complete!');%0A%0A
 // N
@@ -3899,12 +3899,811 @@
 iveMaps,%0A);%0A
+%0A// Patching react-native-utils see https://github.com/Microsoft/react-native-code-push/issues/1276#issuecomment-424720093 for more info%0Aconst RCTUtilsMPath = path.join(%0A  __dirname,%0A  '..',%0A  'node_modules',%0A  'react-native',%0A  'React',%0A  'Base',%0A  'RCTUtils.m',%0A);%0A%0Alog('Patching RCTUtils.m....');%0Aconst RCTUtilsM = fs.readFileSync(RCTUtilsMPath, 'utf-8');%0A%0Afs.writeFileSync(%0A  RCTUtilsMPath,%0A  RCTUtilsM.replace(%0A    'image = %5BUIImage imageWithData:fileData%5D;',%0A    %60CGFloat scale = 1.0;%0A    if (%5B%5BimageURL absoluteString%5D hasSuffix: @%22@3x.png%22%5D) %7B%0A      scale = 3.0;%0A    %7D else if (%5B%5BimageURL absoluteString%5D hasSuffix: @%22@2x.png%22%5D) %7B%0A      scale = 2.0;%0A    %7D%0A    image = %5BUIImage imageWithData:fileData scale: scale%5D;%60,%0A  ),%0A);%0Alog('Done patching RCTUtils.m');%0A%0Alog('Configuration complete!');%0A

Patch react-native RCTUtils.m to work with code-push