/*
	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 detectCordova = mdoCordovaSupport.detect;
var parseCordova = mdoCordovaSupport.parse;
var getAppConfigKeys = mdoCordovaSupport.getAppConfigKeys;
var setAppConfigKey = mdoCordovaSupport.setAppConfigKey;

var moduleName = 'detectCordovaBrowser';

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 browserProj,
        d = Q.defer();

    detectCordova()
    .then(function (configXMLPath) {
      var cordovaBrowserPath = 'platforms/browser';

      if(configXMLPath) {
          log.silly(moduleName, 'Attempting to find manifest.webapp to detect if below platform/browser');
          browserProj = findup('manifest.webapp');

          //We are trying to protect against apps within apps, like having a Cordova app within an Browser apps
          if(browserProj && browserProj.indexOf(cordovaBrowserPath) < 0) {
            log.silly(moduleName, 'Found manifest.webapp \'' + browserProj + '\' that does not live in Cordova project. We must have a project in a project');
            browserProj = null;
          }
          //If we weren't below "inside" the platforms/browser folder then we should check if the platform exists from Cordova root
          if(!browserProj) {
              //If we are below platforms at this point it is because we are in a different platform
              //else check that the browser dir is present in platforms folder
              var belowPlatforms = process.cwd().indexOf(path.sep + 'platforms' + path.sep);
              if(belowPlatforms < 0) {
                log.silly(moduleName, 'Checking for platforms/browser existence');
                var browserPlatPath = path.resolve(configXMLPath, '..', cordovaBrowserPath);
                try {
                    fs.statSync(browserPlatPath);
                    log.silly(moduleName, 'Found platforms/browser at: ' + browserPlatPath);
                    //If statSync doesn't throw error our path should exist
                    browserProj = browserPlatPath;
                } catch (err) {
                    log.silly(moduleName, 'could not detect platform: cordova-browser');
                }
              }
          } else {
              //browserProj points to actual manifest.webapp file, so go up to the browser dir
              browserProj = path.resolve(browserProj, '..');
          }
        }

        if(browserProj) {
            //Get the appname
            getCordovaAppName(path.resolve(configXMLPath, '..'))
            .then(function(appName) {
                var platformObj = {
                    appName: appName,
                    configXMLPath: configXMLPath,
                    platformPath: browserProj,
                    platformId: 'cordova-browser',
                    platform: 'browser',
                    getAppConfigKeys: getAppConfigKeys,
                    setAppConfigKey: setAppConfigKey
                };
                d.resolve(platformObj);
            });
        } else {
            log.silly(moduleName, 'Could not find browser proj');
            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;
};
