/*
	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 = 'detectCordovaAndroid';

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

    detectCordova()
    .then(function (configXMLPath) {
      var cordovaAndroidPath = 'platforms/android';

      if(configXMLPath) {
          log.silly(moduleName, 'Attempting to find AndroidManifest.xml to detect if below platform/android');
          androidProj = findup('AndroidManifest.xml');

          //We are trying to protect against apps within apps, like having a Cordova app within an Android apps
          if(androidProj && androidProj.indexOf(cordovaAndroidPath) < 0) {
            log.silly(moduleName, 'Found AndroidManifest.xml \'' + androidProj + '\' that does not live in Cordova project. We must have a project in a project');
            androidProj = null;
          }
          //If we weren't below "inside" the platforms/android folder then we should check if the platform exists from Cordova root
          if(!androidProj) {
              //If we are below platforms at this point it is because we are in a different platform
              //else check that the android 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/android existence');
                var androidPlatPath = path.resolve(configXMLPath, '..', cordovaAndroidPath);
                try {
                    fs.statSync(androidPlatPath);
                    log.silly(moduleName, 'Found platforms/android at: ' + androidPlatPath);
                    //If statSync doesn't throw error our path should exist
                    androidProj = androidPlatPath;
                } catch (err) {
                    log.silly(moduleName, 'could not detect platform: cordova-android');
                }
              }
          } else {
              //androidProj points to actual AndroidManifest.xml file, so go up to the android dir
              androidProj = path.resolve(androidProj, '..');
          }
        }

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