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

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

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

    return d.promise;
};

module.exports = function () {
    var windowsProjPath,
        appName,
        d = Q.defer();

    detectCordova()
    .then(function () {
      //If we detected Cordova then we need to reject
      throw new Error('detected Cordova');
    }, 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, '..');
        //Check if windows8.1 or Windows10
        return determineUWPVersion(windowsProjPath);
      } else {
        throw new Error(moduleName, 'could not detect platform: native-windows10');
      }
    })
    .then(function (windowsInfo) {
        var windows10AppDir,
            platform,
            propertiesPath;
        //Variable used for logging only
        var win10DetectionProblem;

        log.silly(moduleName, 'Returned windowsInfo: ' + JSON.stringify(windowsInfo));

        if(windowsInfo.isWindows10) {
          windows10AppDir = getWindows10AppDir(windowsProjPath);
          if(windowsProjPath && windows10AppDir) {
            platform = 'windows';
            // Set client properties path
            propertiesPath = path.resolve(windowsInfo.appxmanifestPath, 'strings',
                                              'mfpclient.resw');
            try {
              fs.statSync(propertiesPath);
            } catch(e) {
              propertiesPath = undefined;
              log.silly(moduleName, 'mfpclient file does not exist');
            }
          } else {
            win10DetectionProblem = 'Error detecting Windows10 due to missing appxmanifest file';
          }
        } else {
          win10DetectionProblem = 'Not a Windows10 project';
        }

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

    return d.promise;
};

function getWindows10AppDir(rootDir) {
  var appxmanifestFile = glob.sync('**/package.appxmanifest', {cwd: rootDir, nocase: true});
  if(appxmanifestFile && appxmanifestFile.length > 0) {
    //We return the concatanation of rootDir with the found file, but we need to go up one level because it points directly to the file and not the directory
    return path.resolve(rootDir, appxmanifestFile[0], '..');
  } else {
    return null;
  }
}
