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

/*
Builds the IOS mfpclient.plist file or updates it if oldData !== undefined
*/
function buildClientPlist(serverInfo, runtime, oldData){
    var server = serverInfo;
    var result = oldData === undefined ? {} : oldData;
    var xmlString = '';
    xmlString += '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n';
    xmlString += '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n';
    xmlString += '<plist version="1.0">\n';
    xmlString += '<dict>\n';

    if(typeof server.path !== 'undefined' && server.path.length > 1){
        xmlString += '\t<key>serverUri</key>\n';
        var serverUri = `${server.protocol}://${server.host}:${server.port}${server.path}`;
        xmlString += '\t<string>' + serverUri + '</string>\n';
    }
    else{

        if(result["serverUri"] !== undefined){
            xmlString += '\t<key>serverUri</key>\n';
            var serverUri = "";
            xmlString += '\t<string>' + serverUri + '</string>\n';
        }

        xmlString += '\t<key>protocol</key>\n';
        var protocol =  server.protocol ? server.protocol : result['protocol'];
        protocol = protocol || '';
        xmlString += '\t<string>' + protocol + '</string>\n';

        xmlString += '\t<key>host</key>\n';
        var host = server.host ? server.host : result['host'];
        host = host || '';
        xmlString += '\t<string>' + host + '</string>\n';

        xmlString += '\t<key>port</key>\n';
        var port = server.port ? server.port : result['port'];
        port = port || '';
        xmlString += '\t<string>' + port + '</string>\n';

        // <key>wlServerContext</key>
        xmlString += '\t<key>wlServerContext</key>\n';
        var runtimeVal = runtime ? '/'+runtime+'/' : result['wlServerContext'];
        runtimeVal = runtimeVal || '';
        xmlString += '\t<string>' + runtimeVal + '</string>\n';

        // <key>languagePreferences</key>
        xmlString += '\t<key>languagePreferences</key>\n';
        var languagePreferencesValue = result['languagePreferences'] === undefined ? 'en' : result['languagePreferences'];
        xmlString += '\t<string>' + languagePreferencesValue + '</string>\n';
    }
    xmlString += '</dict>\n';
    xmlString += '</plist>\n';

    return xmlString;
}

module.exports = buildClientPlist;
