/*
	Licensed Material - Property of IBM

	(C) Copyright 2015 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 fs = require('fs');
var path = require('path');
var log = require('npmlog');
var q = require('q');
var find = require('find');

var moduleName = 'parseNativeBrowser';

module.exports = function(rootDir) {
    var d = q.defer();
    var files = [];
    var clientMetadata = {};

    clientMetadata['app.dotId'] = "";
    clientMetadata['app.name'] = "";

	try {
        files = find.fileSync(/\.js$/, rootDir); //find all js files
        var appIDSet = false;
        if (files.length !== 0) {
            for (var l = 0; l < files.length; l++) {
                //if application id has been found, end search
                if (appIDSet) {
                    break;
                }

                var fileInfo = fs.readFileSync(files[l]);
                //try to find applicationId
                var splitIndex = fileInfo.toString().split('\n');
                for (var k = 0; k < splitIndex.length; k++) {
                    var appIdLine = splitIndex[k].indexOf('applicationId');
                    if (appIdLine > -1) {
                        var appIdLineCut = splitIndex[k].substr(appIdLine + 13); //cut off applicationId part of string
                        var appID = appIdLineCut.match('[a-zA-Z0-9.]+');
                        if (appID) {
                            log.silly(moduleName, 'Found application id: ' + appID);
                            appIDSet = true;
                            clientMetadata['app.dotId'] = appID[0];
                            break;
                        }
                    }
                }
            }
        }

        if (!appIDSet) {
            log.silly(moduleName, 'Could not find browser info so you will be prompted');
        }

    } catch (err) {
        log.silly(moduleName, 'Error parsing browser info.' + err.message);
        d.reject();
    }

    //attempting to find app name - if not found server defaults it to the app id
    try {
        fs.statSync(path.join(rootDir,"package.json"));
        var appPackage = require(path.join(rootDir,"package.json"));
        clientMetadata['app.name'] = appPackage.name;
        log.silly(moduleName, 'Found app name: ' + appPackage.name);
    } catch (err) {
        log.silly(moduleName, 'Could not find app name - will default to application id');
    }

    d.resolve(clientMetadata);
    return d.promise;
};
