"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.configureLaunchAssetsAsync = configureLaunchAssetsAsync;

function _fsExtra() {
  const data = _interopRequireDefault(require("fs-extra"));

  _fsExtra = function () {
    return data;
  };

  return data;
}

function _path() {
  const data = _interopRequireDefault(require("path"));

  _path = function () {
    return data;
  };

  return data;
}

function _rimraf() {
  const data = _interopRequireDefault(require("rimraf"));

  _rimraf = function () {
    return data;
  };

  return data;
}

function _xmldom() {
  const data = require("xmldom");

  _xmldom = function () {
    return data;
  };

  return data;
}

function _ExponentTools() {
  const data = require("./ExponentTools");

  _ExponentTools = function () {
    return data;
  };

  return data;
}

function IosWorkspace() {
  const data = _interopRequireWildcard(require("./IosWorkspace"));

  IosWorkspace = function () {
    return data;
  };

  return data;
}

function _StandaloneContext() {
  const data = _interopRequireDefault(require("./StandaloneContext"));

  _StandaloneContext = function () {
    return data;
  };

  return data;
}

function _Logger() {
  const data = _interopRequireDefault(require("./Logger"));

  _Logger = function () {
    return data;
  };

  return data;
}

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const logger = _Logger().default.withFields({
  buildPhase: 'configuring NSBundle'
});

const ASPECT_FILL = 'scaleAspectFill';
const ASPECT_FIT = 'scaleAspectFit';
const backgroundImageViewID = 'Bsh-cT-K4l';
const backgroundViewID = 'OfY-5Y-tS4';

function _backgroundColorFromHexString(hexColor) {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hexColor);

  if (!result || result.length < 4) {
    // Default to white if we can't parse the color. We should have 3 matches.
    logger.warn('Unable to parse color: ', hexColor, ' result:', result);
    return {
      r: 1,
      g: 1,
      b: 1
    };
  }

  const r = parseInt(result[1], 16) / 255;
  const g = parseInt(result[2], 16) / 255;
  const b = parseInt(result[3], 16) / 255;
  return {
    r,
    g,
    b
  };
}

function _setBackgroundColor(manifest, dom) {
  let backgroundColorString;

  if (manifest.ios && manifest.ios.splash && manifest.ios.splash.backgroundColor) {
    backgroundColorString = manifest.ios.splash.backgroundColor;
  } else if (manifest.splash && manifest.splash.backgroundColor) {
    backgroundColorString = manifest.splash.backgroundColor;
  } // Default to white


  if (!backgroundColorString) {
    backgroundColorString = '#FFFFFF';
  }

  const {
    r,
    g,
    b
  } = _backgroundColorFromHexString(backgroundColorString);

  const backgroundViewNode = dom.getElementById(backgroundViewID);
  const backgroundViewColorNodes = backgroundViewNode.getElementsByTagName('color');
  let backgroundColorNode;

  for (let i = 0; i < backgroundViewColorNodes.length; i++) {
    const node = backgroundViewColorNodes[i];

    if (node.parentNode.getAttribute('id') !== backgroundViewID) {
      continue;
    }

    if (node.getAttribute('key') === 'backgroundColor') {
      backgroundColorNode = node;
      break;
    }
  }

  if (backgroundColorNode) {
    backgroundColorNode.setAttribute('red', r);
    backgroundColorNode.setAttribute('green', g);
    backgroundColorNode.setAttribute('blue', b);
  }
}

async function _saveImageAssetsAsync(context) {
  let tabletImagePathOrUrl, phoneImagePathOrUrl;

  if (context.type === 'user') {
    // copy images from local project
    const exp = context.data.exp;

    if (exp.ios && exp.ios.splash && exp.ios.splash.image) {
      phoneImagePathOrUrl = exp.ios.splash.image;

      if (exp.ios.splash.tabletImage) {
        tabletImagePathOrUrl = exp.ios.splash.tabletImage;
      }
    } else if (exp.splash && exp.splash.image) {
      phoneImagePathOrUrl = exp.splash.image;
    }
  } else {
    // use uploaded assets from published project
    const manifest = context.data.manifest;

    if (manifest.ios && manifest.ios.splash && manifest.ios.splash.imageUrl) {
      phoneImagePathOrUrl = manifest.ios.splash.imageUrl;

      if (manifest.ios.splash.tabletImageUrl) {
        tabletImagePathOrUrl = manifest.ios.splash.tabletImageUrl;
      }
    } else if (manifest.splash && manifest.splash.imageUrl) {
      phoneImagePathOrUrl = manifest.splash.imageUrl;
    }
  }

  if (!phoneImagePathOrUrl) {
    return;
  }

  const outputs = [];

  if (!tabletImagePathOrUrl) {
    outputs.push({
      pathOrUrl: phoneImagePathOrUrl,
      filename: 'launch_background_image.png'
    });
  } else {
    outputs.push({
      pathOrUrl: phoneImagePathOrUrl,
      filename: 'launch_background_image~iphone.png'
    });
    outputs.push({
      pathOrUrl: tabletImagePathOrUrl,
      filename: 'launch_background_image.png'
    });
  }

  const {
    supportingDirectory
  } = IosWorkspace().getPaths(context);
  const projectRoot = context.type === 'user' ? context.data.projectPath : supportingDirectory;
  outputs.forEach(async output => {
    const {
      pathOrUrl,
      filename
    } = output;

    const destinationPath = _path().default.join(supportingDirectory, filename);

    await (0, _ExponentTools().saveImageToPathAsync)(projectRoot, pathOrUrl, destinationPath);
  });
}

function _setBackgroundImageResizeMode(manifest, dom) {
  let backgroundViewMode = (() => {
    let mode;

    if (!manifest) {
      return ASPECT_FIT;
    }

    if (manifest.ios && manifest.ios.splash && manifest.ios.splash.resizeMode) {
      mode = manifest.ios.splash.resizeMode;
    } else if (manifest.splash && manifest.splash.resizeMode) {
      mode = manifest.splash.resizeMode;
    }

    return mode === 'cover' ? ASPECT_FILL : ASPECT_FIT;
  })();

  const backgroundImageViewNode = dom.getElementById(backgroundImageViewID);

  if (backgroundImageViewNode) {
    backgroundImageViewNode.setAttribute('contentMode', backgroundViewMode);
  }
}

async function _copyIntermediateLaunchScreenAsync(context, launchScreenPath) {
  let splashTemplateFilename;

  if (context.type === 'user') {
    const {
      supportingDirectory
    } = IosWorkspace().getPaths(context);
    splashTemplateFilename = _path().default.join(supportingDirectory, 'LaunchScreen.xib');
  } else {
    // TODO: after shell apps use detached workspaces,
    // we can just do this with the workspace's copy instead of referencing expoSourcePath.
    const expoTemplatePath = _path().default.join(context.data.expoSourcePath, '..', 'exponent-view-template', 'ios');

    splashTemplateFilename = _path().default.join(expoTemplatePath, 'exponent-view-template', 'Supporting', 'LaunchScreen.xib');
  }

  await (0, _ExponentTools().spawnAsyncThrowError)('/bin/cp', [splashTemplateFilename, launchScreenPath], {
    stdio: 'inherit'
  });
}

async function configureLaunchAssetsAsync(context, intermediatesDirectory) {
  logger.info('Configuring iOS Launch Screen...');

  _fsExtra().default.mkdirpSync(intermediatesDirectory);

  const {
    supportingDirectory
  } = IosWorkspace().getPaths(context);
  const config = context.config;

  const splashIntermediateFilename = _path().default.join(intermediatesDirectory, 'LaunchScreen.xib');

  let xibFile = null;

  if (context.type === 'user') {
    xibFile = context.data.exp.ios && context.data.exp.ios.splash && context.data.exp.ios.splash.xib;
  } else {
    xibFile = context.data.manifest.ios && context.data.manifest.ios.splash && context.data.manifest.ios.splash.xibUrl;
  }

  if (xibFile) {
    if (context.type === 'user') {
      const sourcePath = _path().default.resolve(context.data.projectPath, xibFile);

      await (0, _ExponentTools().spawnAsyncThrowError)('/bin/cp', [sourcePath, splashIntermediateFilename], {
        stdio: 'inherit'
      });
    } else {
      await (0, _ExponentTools().saveUrlToPathAsync)(xibFile, splashIntermediateFilename);
    }
  } else {
    await _copyIntermediateLaunchScreenAsync(context, splashIntermediateFilename);

    if ((0, _ExponentTools().manifestUsesSplashApi)(config, 'ios')) {
      await (0, _ExponentTools().transformFileContentsAsync)(splashIntermediateFilename, fileString => {
        const parser = new (_xmldom().DOMParser)();
        const serializer = new (_xmldom().XMLSerializer)();
        const dom = parser.parseFromString(fileString);

        _setBackgroundColor(config, dom);

        _setBackgroundImageResizeMode(config, dom);

        return serializer.serializeToString(dom);
      });
      await _saveImageAssetsAsync(context);
    }
  }

  if (context.type === 'user') {
    await (0, _ExponentTools().spawnAsyncThrowError)('/bin/cp', [splashIntermediateFilename, _path().default.join(supportingDirectory, 'LaunchScreen.xib')], {
      stdio: 'inherit'
    });
  } else {
    const splashOutputFilename = _path().default.join(supportingDirectory, 'Base.lproj', 'LaunchScreen.nib');

    await (0, _ExponentTools().spawnAsyncThrowError)('ibtool', ['--compile', splashOutputFilename, splashIntermediateFilename]);

    const generatedUnnecessaryNib = _path().default.join(supportingDirectory, 'LaunchScreen.nib');

    if (_fsExtra().default.existsSync(generatedUnnecessaryNib)) {
      _rimraf().default.sync(generatedUnnecessaryNib);
    }
  }
}
//# sourceMappingURL=../__sourcemaps__/detach/IosLaunchScreen.js.map