/*
	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 glob = require('glob');
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 appConfig = require('./appConfig');
var getAppConfigKeys = appConfig.getAppConfigKeys;
var setAppConfigKey = appConfig.setAppConfigKey;

var moduleName = 'detectNativeAndroid';

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

    detectCordova()
    .then(function () {
        //If Cordova was detected we need to reject
        d.reject();
    }, function () {
      log.silly(moduleName, 'Attempting to find gradle folder');
      //Find gradle folder first then we can find the main .iml file off of that
      var gradleFolderPath = findup('gradle');
      if(gradleFolderPath) {
          log.silly(moduleName, 'gradle folder found at: ' + gradleFolderPath);
          log.silly(moduleName, 'attempting to find build.gradle file');
          androidProj = findup('build.gradle', {cwd: gradleFolderPath});
          log.silly(moduleName, 'Found build.gradle at: ' + androidProj);
          androidProj = path.resolve(androidProj, '..');

          //Verify we are actually android by finding the AndroidManifest.xml
          log.silly(moduleName, 'attempting to find AndroidManifest.xml');
          var manifestFile = glob.sync('**/AndroidManifest.xml', {cwd: androidProj});
          if(manifestFile.length <= 0) {
            log.silly(moduleName, 'Could not find AndroidManifest.xml file');
            androidProj = null;
          }
        }
        if(androidProj) {
            var appName = getAndroidAppName(gradleFolderPath);

            // Set client properties path
            propertiesPath = path.resolve(androidProj, 'app', 'src', 'main',
                                          'assets', 'mfpclient.properties');
            try {
              fs.statSync(propertiesPath);
            } catch(e) {
              propertiesPath = undefined;
              log.silly(moduleName, 'mfpclient file does not exist');
            }

            d.resolve({
                appName: appName,
                platformPath: androidProj,
                platformId: 'native-android',
                platform: 'android',
                propertiesPath: propertiesPath,
                getAppConfigKeys: getAppConfigKeys,
                setAppConfigKey: setAppConfigKey
            });
        } else {
            log.silly(moduleName, 'could not detect platform: native-android');
            d.reject();
        }
    })
    .catch(function (err) {
      if(err && err.message)
        log.silly(moduleName, 'Error detecting: ' + err.message);
      d.reject();
    });

    return d.promise;
};

function getAndroidAppName(gradleFolderPath) {
  var appName;
  var imlFile = findup('*.iml', {cwd: gradleFolderPath});
  if(imlFile) {
    appName = path.basename(imlFile, '.iml');
  } else {
    var nameSplit = gradleFolderPath.split(path.sep);
    appName = nameSplit[nameSplit.length - 2];
  }

  return appName;
}
