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

var moduleName = 'detectNativeWindows8';

var determineUWPVersion = function (rootDir) {
    var d = Q.defer();

    parseAppXManifest(rootDir)
    .then(function (result) {
        d.resolve({
          isWindows10: result['isWindows10'],
          hasPhone: result['hasPhoneIdentity'],
          appxmanifestPath: path.resolve(result['appxmanifestPath'], '..')
        });
    }, function () {
        d.reject('could not parse appxmanifest');
    });

    return d.promise;
};

module.exports = function () {
    var windowsProjPath,
        windowsFolderPath,
        isWindows = false,
        appName,
        cwd = process.cwd(),
        d = Q.defer();

    detectCordova()
    .then(function () {
        //If we detected Cordova then we need to reject
        throw new Error('cordova detected');
    }, function () {
      log.silly(moduleName, 'Attempting to find .sln file');
      windowsProjPath = findup('*.sln');
      if(windowsProjPath) {
        log.silly(moduleName, 'Found .sln file at: ' + windowsProjPath);
        appName = path.basename(windowsProjPath, '.sln');
        windowsProjPath = path.resolve(windowsProjPath, '..');
      } else {
        throw new Error('could not detect platform: native-windows8');
      }
    })
    .then(function () {
      //Check for Windows or WindowsPhone folders
      var appNameWindowsFolder = appName + '.Windows';
      log.silly(moduleName, 'Attempting to find folder \'' + appNameWindowsFolder + '\' or \'Windows\'');
      windowsFolderPath = glob.sync('{' + appNameWindowsFolder + ',Windows}', {cwd: windowsProjPath})[0];
      //If you couldn't find at the root level the appName.Windows or Windows folder then search for a .Windows below root
      if(!windowsFolderPath) {
        log.silly(moduleName, 'could not folder \'' + appNameWindowsFolder + '\' or \'Windows\'');
        log.silly(moduleName, 'attempting to find **/*.Windows');
        windowsFolderPath = glob.sync('**/*.Windows', {cwd: windowsProjPath})[0];
      }

      if(windowsFolderPath) {
        log.silly(moduleName, 'found windows folder at: ' + windowsFolderPath);
        windowsFolderPath = path.join(windowsProjPath, windowsFolderPath);
        return determineUWPVersion(windowsFolderPath);
      } else {
        log.silly(moduleName, 'no Windows folder found');
        return determineUWPVersion(windowsProjPath);
      }
    })
    .then(function (windowsInfo) {
      log.silly(moduleName, 'Returned windowsInfo: ' + JSON.stringify(windowsInfo));
      //There is discussion of possibly treating Windows8 & Windows10 projects seperately, leaving logic in for now.
      if(!windowsInfo.isWindows10 && windowsProjPath) {
        if(!windowsInfo.hasPhone) {
          if(windowsFolderPath && windowsFolderPath.length > 0) {
            //Check if in or below WindowsPhone folder
            var projectTypePath = findup('Package.appxmanifest', {cwd: cwd, nocase: true});
            if(typeof(projectTypePath) === 'string') {
              isWindows = projectTypePath.indexOf('Windows') >= 0 && projectTypePath.indexOf('WindowsPhone') < 0;
              log.silly(moduleName, 'found appxmanifest at: ' + projectTypePath + ' to determine if below Windows folder');
            } else {
              isWindows = true;
            }
          } else {
            isWindows = true;
          }
        }

        if(isWindows) {
          var platform = 'windows8';

          // Set client properties path
          var propertiesPath = path.resolve(windowsInfo.appxmanifestPath, 'strings', 'mfpclient.resw');

          try {
            fs.statSync(propertiesPath);
          } catch(e) {
            propertiesPath = undefined;
            log.silly(moduleName, 'mfpclient file does not exist');
          }

          d.resolve({
            appName: appName,
            platformPath: windowsProjPath,
            windowsEnvPath: windowsInfo.appxmanifestPath,
            platformId: 'native-windows8',
            platform: platform,
            propertiesPath: propertiesPath,
            getAppConfigKeys: getAppConfigKeys,
            setAppConfigKey: setAppConfigKey
          });
        } else {
          log.silly(moduleName, 'did not detect windows8 project');
          d.reject();
        }
      } else {
        log.silly(moduleName, 'did not detect windows8 project');
        d.reject();
      }
    })
    .catch(function (err) {
      if(err && err.message)
        log.silly(moduleName, 'Error detecting: ' + err.message);
      d.reject();
    });

    return d.promise;
};
