const path = require('path');
const log = require('npmlog');
const https = require('https');
const fs = require('fs');
const url = require('url');
const getProjectMetadata = require('./projectMetadata');
const glob = require('glob');
const childProcess = require('child_process');

const APPHUB_API = 'https://api.apphub.io/v1/upload';

log.heading = 'rnpm-apphub';

/**
 * Updates project and linkes all dependencies to it
 *
 * If optional argument [packageName] is provided, it's the only one that's checked
 */
module.exports = function link(config, args) {
  const project = config.getProjectConfig();

  if (!project) {
    log.error('ERRPACKAGEJSON', `No package found. Are you sure it's a React Native project?`);
    return;
  }

  if (!project.ios) {
    log.error('ERRPACKAGEJSON', `No ios project found. Currently AppHub is only for iOS`);
    return;
  }

  /*
   * Find .ipa to upload
   */

  // TODO: would be nice to reuse that from core
  const GLOB_EXCLUDE_PATTERN = ['node_modules/**', 'Examples/**', 'examples/**', 'Pods/**'];

  const ipas = glob.sync('**/*.ipa', {
    pwd: project.ios.sourceDir,
    ignore: GLOB_EXCLUDE_PATTERN,
  });

  if (ipas.length === 0) {
    log.error('ERRIPA', `No .ipa files found. Please, export the application`);
    return;
  }

  /*
   * Filling the metadata from plist and last git commit
   */
  const lastGitMessage = childProcess.execSync('git log -1 --pretty=%B | cat').toString().split('\n')[0];
  const metadata = getProjectMetadata(project);

  /*
   * Put file onto the server
   */
  if (args.length < 2) {
    log.error('ERRTOKENS', 'No AppID and AppTokens provided. Please obtain them from AppHub dashbaord');
    return;
  }

  log.info('Uploading build...', metadata.version, lastGitMessage);

  const result = childProcess.execSync(`
    curl -X PUT \
     -H "X-AppHub-Application-ID: ${args[0]}" \
     -H "X-AppHub-Application-Secret: ${args[1]}" \
     -H "Content-Type: application/zip" \
     -H 'X-AppHub-Build-Metadata: {
           "target": "all",
           "name": "${metadata.version}",
           "description": "${lastGitMessage} // by rnpm-plugin-apphub",
           "app_versions": ["${metadata.shortVersion}"]
      }' \
      -L https://api.apphub.io/v1/upload \
      --upload-file ./build/moneyed.ipa
  `);

  log.info(result);

};

@@ -146,20 +146,17 @@
 ;%0Aconst 
-getP
+p
 rojectMe
@@ -270,16 +270,85 @@
 ocess');
+%0Aconst uuid = require('node-uuid');%0Aconst mkdirp = require('mkdirp');
 %0A%0Aconst 
@@ -942,409 +942,870 @@
   * 
-Find .ipa to upload%0A   */%0A%0A  // TODO: would be nice to reuse that from core%0A  const GLOB_EXCLUDE_PATTERN = %5B'node_modules/**', 'Examples/**', 'examples/**', 'Pods/**'%5D;%0A
+Build application .zip%0A   */%0A%0A   const plistFile = projectMetadata.getPlistPath(project)%0A   const outputZip = path.join(process.cwd().replace(/ /g, '%5C%5C '), './build/app.zip');%0A   const tmpDir = path.join('/tmp', 'apphub', uuid.v4());
 %0A  
+ 
 const 
-ipas = glob.sync('**/*.ipa', %7B%0A    pwd: project.ios.sourceDir,%0A    ignore: GLOB_EXCLUDE_PATTERN
+buildDir = path.join(tmpDir, 'ios');%0A   mkdirp.sync(buildDir);%0A%0A   var options = %5B%0A     '--entry-file', 'index.ios.js',%0A     '--dev', false,%0A     '--bundle-output', path.join(buildDir, 'main.jsbundle'),%0A     '--assets-dest', buildDir,%0A     '--platform', 'ios'
 ,%0A  
-%7D)
+ %5D
 ;%0A%0A  
-if (ipas.length === 0) %7B%0A    log.error('ERRIPA', %60No .ipa files found. Please, export the application%60);%0A    return
+ var cmds = %5B%0A     'node node_modules/react-native/local-cli/cli.js bundle ' + options.join(' '),%0A     'cp ' + plistFile + ' ' + buildDir,%0A     'cd ' + tmpDir + ' && zip -r ' + outputZip + ' ios',%0A   %5D;%0A   for (var i = 0; i %3C cmds.length; i++) %7B%0A     var cmd = cmds%5Bi%5D;%0A     childProcess.execSync(cmd, %7B stdio: %5B0, 1, 2%5D %7D, %7B cwd: process.cwd()%7D)
 ;%0A
+ 
   %7D%0A
@@ -1998,16 +1998,33 @@
 adata = 
+ projectMetadata.
 getProje
@@ -2044,16 +2044,100 @@
 oject);%0A
+  if (!metadata) %7B%0A    log.error('ERRPLIST', '.plist is not found');%0A    return;%0A  %7D
 %0A  /*%0A  
@@ -2907,19 +2907,15 @@
 ild/
-moneyed.
+app.z
 ip
-a
 %0A  %60

update to latest apphub