/*
	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 fs = require('fs');

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

var moduleName = 'detectNativeBrowser';

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

    detectCordova()
    .then(function () {
        //If Cordova was detected we need to reject
        d.reject();
    }, function () {
        log.silly(moduleName, 'Attempting to find index.html file');
        browserProj = findup('*/index.html');
        log.silly(moduleName, 'Found index.html file at: ' + browserProj);
		browserProj = path.resolve(browserProj, '..');

      log.silly(moduleName, 'Attempting to find ibm-mfp-web-sdk folder');
      var webSdkFolder = findup('ibm-mfp-web-sdk') ? findup('ibm-mfp-web-sdk') : findup(path.join('node_modules', 'ibm-mfp-web-sdk'));
      if(webSdkFolder) {
        log.silly(moduleName, 'Found ibm-mfp-web-sdk folder at: ' + webSdkFolder);

        //attempting to find app name - if not found server defaults it to the app id
        var appName = "";
        try {
            fs.statSync(path.join(browserProj,"package.json"));
            var appPackage = require(path.join(browserProj,"package.json"));
            appName = appPackage.name;
        } catch (err) {
            log.silly(moduleName, 'Could not find app name - will default to application id');
        }

        d.resolve({
            appName: appName,
            platformPath: browserProj,
            platformId: 'native-browser',
            platform: 'browser'
        });
      } else {
          log.silly(moduleName, 'Could not detect platform: browser. Please make sure you are running from the web resources dir if this is a web app');
          d.reject();
      }
    })
    .catch(function (err) {
      if(err && err.message)
        log.silly(moduleName, 'Error detecting: ' + err.message);
      d.reject();
    });

    return d.promise;
};
