/*
	Licensed Material - Property of IBM

	(C) Copyright 2015, 2016 IBM Corp.

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/


'use strict';

var findup = require('findup-sync');
var fs = require('fs');
var log = require('npmlog');
var path = require('path');
var Q = require('q');

//private
var mdoCordovaSupport = require('mdo-cordova-support');
var parseCordova = mdoCordovaSupport.parse;
var detectCordova = mdoCordovaSupport.detect;
var getAppConfigKeys = mdoCordovaSupport.getAppConfigKeys;
var setAppConfigKey = mdoCordovaSupport.setAppConfigKey;

var moduleName = 'detectCordovaIOS';

var getCordovaAppName = function(configXMLDir) {
    var d = Q.defer();
    parseCordova(configXMLDir)
    .then(function (appInfo) {
        d.resolve(appInfo['app.name']);
    }, function () {
        d.resolve(path.basename(configXMLDir));
    });

    return d.promise;
};

module.exports = function () {
    var iosProj,
        d = Q.defer();

    detectCordova()
    .then(function (configXMLPath) {
        var cordovaIOSPath = 'platforms/ios';
        if(configXMLPath) {
          log.silly(moduleName, 'Attempting to find *.xcodeproj to detect if below platform/ios');
          iosProj = findup('*.xcodeproj');

          //We are trying to protect against apps within apps, so you have a Cordova app that is within an IOS app
          if(iosProj && iosProj.indexOf(cordovaIOSPath) < 0) {
            log.silly(moduleName, 'Found .xcodeproj \'' + iosProj + '\' that does not live in Cordova project. We must have a project in a project');
            iosProj = null;
          }

          //If we weren't below "inside" the platforms/android folder then we should check if the platform exists from Cordova root
          if(!iosProj) {
              //If we are below platforms we must be in a platform so don't do the statSync
              var belowPlatforms = process.cwd().indexOf(path.sep +  'platforms' + path.sep);
              if(belowPlatforms < 0) {
                log.silly(moduleName, 'Checking for platforms/ios existence');
                var iosPlatPath = path.resolve(configXMLPath, '..', cordovaIOSPath);
                try {
                    fs.statSync(iosPlatPath);
                    log.silly(moduleName, 'Found platforms/ios at: ' + iosPlatPath);
                    //If statSync doesn't throw error our path exists
                    iosProj = iosPlatPath;
                } catch (err) {
                    log.silly(moduleName, 'could not detect platform: cordova-ios');
                }
              }
            } else {
                //androidProj points to actual AndroidManifest.xml file, so go up to the android dir
                iosProj = path.resolve(iosProj, '..');
            }
        }

        if(iosProj) {
            //Get the appname
            getCordovaAppName(path.resolve(configXMLPath, '..'))
            .then(function(appName) {
                var platformObj = {
                    appName: appName,
                    configXMLPath: configXMLPath,
                    platformPath: iosProj,
                    platformId: 'cordova-ios',
                    platform: 'ios',
                    getAppConfigKeys: getAppConfigKeys,
                    setAppConfigKey: setAppConfigKey
                };
                d.resolve(platformObj);
            });
        } else {
            log.silly(moduleName, 'Could not detect cordova-ios');
            d.reject();
        }
    })
    .catch(function (err) {
        //If there was an error with detectCordova
        if(err && err.message)
          log.silly(moduleName, 'Error detecting: ' + err.message);
        d.reject();
    });

    return d.promise;
};
