/*
	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 log = require('npmlog');
var path = require('path');
var Q = require('q');
var glob = require('glob');

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

var moduleName = 'detectNativeIOS';

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

    detectCordova()
    .then(function () {
        //If Cordova was detected we need to reject
        d.reject();
    }, function () {
      log.silly(moduleName, 'Attempting to find .xcodeproj');
      iosProj = findup('*.xcodeproj');
      if(iosProj) {
        log.silly(moduleName, 'Found .xcodeproj at: ' + iosProj);
        var appName = path.basename(iosProj, '.xcodeproj');
        iosProj = path.resolve(iosProj, '..');
        var clientFiles = glob.sync('**/mfpclient.plist', {cwd: iosProj});
        var propertiesPath = clientFiles.length > 0 ?
                             path.resolve(iosProj, clientFiles[0]) :
                             undefined;
        d.resolve({
            appName: appName,
            platformPath: iosProj,
            platformId: 'native-ios',
            platform: 'ios',
            propertiesPath: propertiesPath,
            getAppConfigKeys: getAppConfigKeys,
            setAppConfigKey: setAppConfigKey,
        });
      } else {
          log.silly(moduleName, 'could not detect platform: native-ios');
          d.reject();
      }
    })
    .catch(function (err) {
      if(err && err.message)
        log.silly(moduleName, 'Error detecting: ' + err.message);
      d.reject();
    });

    return d.promise;
};
