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

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

var moduleName = 'detectCordovaWindowsPhone8';

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

    detectCordova()
    .then(function (configXMLPath) {
        var cordovaWindowsPath = 'platforms/windows';
        if(configXMLPath) {
          log.silly(moduleName, 'Attempting to find *.phone.appxmanifest to detect if below platform/windows');
          windowsProj = findup('*.phone.appxmanifest');

          //We are trying to protect against apps within apps, so you have a Cordova app that is within an Windows app
          if(windowsProj && windowsProj.indexOf(cordovaWindowsPath) < 0) {
            log.silly(moduleName, 'Found *.phone.appxmanifest \'' + windowsProj + '\' that does not live in Cordova project. We must have a project in a project');
            windowsProj = null;
          }
          //If we weren't below "inside" the platforms/android folder then we should check if the platform exists from Cordova root
          if(!windowsProj) {
              //If we are below platforms we must be in a platform so don't do the statSync
              var belowPlatforms = process.cwd().indexOf(path.sep + 'platforms' + path.sep);
              if(belowPlatforms < 0) {
                log.silly(moduleName, 'Checking for platforms/windows existence');
                var windowsPlatPath = path.resolve(configXMLPath, '..', cordovaWindowsPath);
                try {
                    fs.statSync(windowsPlatPath);
                    log.silly(moduleName, 'Found platforms/windows at: ' + windowsPlatPath);
                    //If statSync doesn't throw error our path should exist
                    log.silly(moduleName, 'Checking for Windows8Phone appxmanifest');
                    var isWindows8Phone = glob.sync('*.phone.appxmanifest', {cwd: windowsPlatPath});
                    if(isWindows8Phone.length > 0) {
                      log.silly(moduleName, 'Found Windows8Phone appxmanifest at: ' + isWindows8Phone);
                      windowsProj = windowsPlatPath;
                    }
                } catch (err) {
                    log.silly(moduleName, 'could not detect platform: cordova-windows8phone');
                }
              }
            } else {
                //windowsProj points to actual .appxmanifest file, so go up to the windows dir
                log.silly(moduleName, 'Found appxmanifest for Windows8Phone at: ' + windowsProj);
                windowsProj = path.resolve(windowsProj, '..');
            }
        }

        if(windowsProj) {
            //Get the appname
            getCordovaAppName(path.resolve(configXMLPath, '..'))
            .then(function(appName) {
                var platformObj = {
                    appName: appName,
                    configXMLPath: configXMLPath,
                    platformPath: windowsProj,
                    platformId: 'cordova-windows8phone',
                    platform: 'windowsphone8'
                };
                d.resolve(platformObj);
            });
        } else {
            log.silly(moduleName, 'could not detect cordova-windows8phone');
            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;
};
