"use strict";
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.String = void 0;
const codemodel_v3_1 = require("@azure-tools/codemodel-v3");
const codegen_1 = require("@azure-tools/codegen");
const codegen_csharp_1 = require("@azure-tools/codegen-csharp");
const codegen_csharp_2 = require("@azure-tools/codegen-csharp");
const codegen_csharp_3 = require("@azure-tools/codegen-csharp");
const clientruntime_1 = require("../clientruntime");
const codemodel_1 = require("@autorest/codemodel");
const primitive_1 = require("./primitive");
/** A ETD for the c# string type. */
class String {
    get defaultOfType() {
        return (0, codegen_csharp_2.toExpression)('null');
    }
    get convertObjectMethod() {
        return 'global::System.Convert.ToString';
    }
    get isNullable() {
        return true;
    }
    get encode() {
        return this.schema.extensions && this.schema.extensions['x-ms-skip-url-encoding'] ? '' : 'global::System.Uri.EscapeDataString';
    }
    deserializeFromContainerMember(mediaType, container, serializedName, defaultValue) {
        switch (mediaType) {
            case codemodel_v3_1.KnownMediaType.Json: {
                // container should be a JsonObject
                const tmpVar = `__${(0, codegen_1.camelCase)(['json', ...(0, codegen_1.deconstruct)(serializedName)])}`;
                return (0, codegen_csharp_2.toExpression)(`If( ${(0, codegen_csharp_2.valueOf)(container)}?.PropertyT<${clientruntime_1.ClientRuntime.JsonString}>("${serializedName}"), out var ${tmpVar}) ? (string)${tmpVar} : (string)${defaultValue}`);
            }
            case codemodel_v3_1.KnownMediaType.Xml: {
                const xTmp = `__${(0, codegen_1.camelCase)(['xml', ...(0, codegen_1.deconstruct)(serializedName)])}`;
                return (0, codegen_csharp_2.toExpression)(`If( ${(0, codegen_csharp_2.valueOf)(container)}?.Element("${serializedName}"), out var ${xTmp}) ? (string)${xTmp} : (string)${defaultValue}`);
            }
            case codemodel_v3_1.KnownMediaType.Header: {
                // HttpResponseHeaders
                const tmp = `__${(0, codegen_1.camelCase)(['header', ...(0, codegen_1.deconstruct)(serializedName)])}`;
                return (0, codegen_csharp_2.toExpression)(`System.Linq.Enumerable.FirstOrDefault(${serializedName}) is string ${tmp} ? ${tmp} : (string)${defaultValue}`);
            }
        }
        return (0, codegen_csharp_2.toExpression)(`${defaultValue} /* deserializeFromContainerMember doesn't support '${mediaType}' ${__filename}*/`);
    }
    deserializeFromNode(mediaType, node, defaultValue) {
        try {
            const tmp = (0, primitive_1.pushTempVar)();
            switch (mediaType) {
                case codemodel_v3_1.KnownMediaType.Json:
                    // node should be a JsonString
                    return (0, codegen_csharp_2.toExpression)(`${node} is ${clientruntime_1.ClientRuntime.JsonString} ${tmp} ? (${this.declaration})(${tmp}.ToString()) : ${defaultValue}`);
                case codemodel_v3_1.KnownMediaType.Xml:
                    return (0, codegen_csharp_2.toExpression)(`${node} is ${codegen_csharp_1.System.Xml.Linq.XElement} ${tmp} ? (string)${tmp} : ${defaultValue}`);
            }
        }
        finally {
            (0, primitive_1.popTempVar)();
        }
        return (0, codegen_csharp_2.toExpression)(`null /* deserializeFromContainer doesn't support '${mediaType}' ${__filename}*/`);
    }
    /** emits an expression serialize this to a HttpContent */
    serializeToContent(mediaType, value, mode) {
        return (0, codegen_csharp_2.toExpression)(`null /* serializeToContent doesn't support '${mediaType}' ${__filename}*/`);
    }
    serializeToNode(mediaType, value, serializedName, mode) {
        switch (mediaType) {
            case codemodel_v3_1.KnownMediaType.Json:
                return (0, codegen_csharp_2.toExpression)(`null != (((object)${value})?.ToString()) ? (${clientruntime_1.ClientRuntime.JsonNode}) new ${clientruntime_1.ClientRuntime.JsonString}(${value}.ToString()) : null`);
            case codemodel_v3_1.KnownMediaType.Xml:
                return (0, codegen_csharp_2.toExpression)(`null != (${value}?.ToString()) ? new ${codegen_csharp_1.System.Xml.Linq.XElement}("${serializedName}",${value}) : null`);
            case codemodel_v3_1.KnownMediaType.QueryParameter: {
                const formatSerializedName = serializedName ? `${serializedName}=` : '';
                if (this.isRequired) {
                    return (0, codegen_csharp_2.toExpression)(`"${formatSerializedName}" + ${this.encode}(${value})`);
                }
                else {
                    return (0, codegen_csharp_2.toExpression)(`(string.IsNullOrEmpty(${value}) ? ${codegen_csharp_1.System.String.Empty} : "${formatSerializedName}" + ${this.encode}(${(0, codegen_csharp_2.valueOf)(value)}))`);
                }
            }
            case codemodel_v3_1.KnownMediaType.Cookie:
            case codemodel_v3_1.KnownMediaType.Header:
            case codemodel_v3_1.KnownMediaType.Text:
            case codemodel_v3_1.KnownMediaType.UriParameter:
                if (this.isRequired) {
                    return (0, codegen_csharp_2.toExpression)(`${this.encode}(${value})`);
                }
                return (0, codegen_csharp_2.toExpression)(`(string.IsNullOrEmpty(${value}) ? ${codegen_csharp_1.System.String.Empty} : ${this.encode}(${value}) )`);
        }
        return (0, codegen_csharp_2.toExpression)(`null /* serializeToNode doesn't support '${mediaType}' ${__filename}*/`);
    }
    /** emits an expression to deserialize content from a string */
    deserializeFromString(mediaType, content, defaultValue) {
        switch (mediaType) {
            case codemodel_v3_1.KnownMediaType.Json: {
                return this.deserializeFromNode(mediaType, clientruntime_1.ClientRuntime.JsonNode.Parse(content), defaultValue);
            }
            case codemodel_v3_1.KnownMediaType.Xml: {
                return this.deserializeFromNode(mediaType, `${codegen_csharp_1.System.Xml.Linq.XElement}.Parse(${content})`, defaultValue);
            }
            case codemodel_v3_1.KnownMediaType.UriParameter: {
                return (0, codegen_csharp_2.toExpression)(content);
            }
        }
        return (0, codegen_csharp_2.toExpression)(`null /* deserializeFromString doesn't support '${mediaType}' ${__filename}`);
    }
    /** emits an expression to deserialize content from a content/response */
    deserializeFromResponse(mediaType, content, defaultValue) {
        switch (mediaType) {
            case codemodel_v3_1.KnownMediaType.Json:
                return (0, codegen_csharp_2.toExpression)(`${content}.Content.ReadAsStringAsync().ContinueWith( body => body.Result)`);
        }
        return (0, codegen_csharp_2.toExpression)(`null /* deserializeFromResponse doesn't support '${mediaType}' ${__filename}*/`);
    }
    serializeToContainerMember(mediaType, value, container, serializedName, mode) {
        const formatSerializedName = serializedName ? `${serializedName}=` : '';
        switch (mediaType) {
            case codemodel_v3_1.KnownMediaType.Json:
                return `AddIf( ${this.serializeToNode(mediaType, value, serializedName, mode)}, "${serializedName}" ,${container}.Add );`;
            case codemodel_v3_1.KnownMediaType.Xml:
                return `AddIf( ${this.serializeToNode(mediaType, value, serializedName, mode)}, ${container}.Add );`;
            case codemodel_v3_1.KnownMediaType.Header:
                // container : HttpRequestHeaders
                return this.isRequired ?
                    `${(0, codegen_csharp_2.valueOf)(container)}.Add("${serializedName}",${value}.ToString());` :
                    (0, codegen_csharp_3.If)(`null != ${value}`, `${(0, codegen_csharp_2.valueOf)(container)}.Add("${serializedName}",${value});`);
            case codemodel_v3_1.KnownMediaType.QueryParameter:
                // gives a name=value for use inside a c# template string($"foo{someProperty}") as a query parameter
                return this.isRequired ?
                    `${formatSerializedName}{${value}.ToString()}` :
                    `{null == ${value} ? ${codegen_csharp_1.System.String.Empty} : $"${formatSerializedName}{${value}.ToString()}"}`;
            case codemodel_v3_1.KnownMediaType.UriParameter:
                // gives a name=value for use inside a c# template string($"foo{someProperty}") as a query parameter
                return this.isRequired ?
                    `(${formatSerializedName}{${value}.ToString()})` :
                    `(null == ${value} ? ${codegen_csharp_1.System.String.Empty}: $"${formatSerializedName}{${value}.ToString()}")`;
        }
        return (`/* serializeToContainerMember doesn't support '${mediaType}' ${__filename}*/`);
    }
    constructor(schema, isRequired) {
        this.schema = schema;
        this.isRequired = isRequired;
        this.isXmlAttribute = false;
    }
    get declaration() {
        return 'string';
    }
    validateValue(eventListener, property) {
        return `
${this.validateMinLength(eventListener, property)}
${this.validateMaxLength(eventListener, property)}
${this.validateRegex(eventListener, property)}
${this.validateEnum(eventListener, property)}
    `.trim();
    }
    validatePresence(eventListener, property) {
        return `await ${eventListener}.AssertNotNull(${(0, codegen_1.nameof)(property.value)},${property});`.trim();
    }
    validateMinLength(eventListener, property) {
        const len = this.schema.minLength;
        if (!len) {
            return '';
        }
        return `await ${eventListener}.AssertMinimumLength(${(0, codegen_1.nameof)(property.value)},${property},${len});`;
    }
    validateMaxLength(eventListener, property) {
        const len = this.schema.maxLength;
        if (!len) {
            return '';
        }
        return `await ${eventListener}.AssertMaximumLength(${(0, codegen_1.nameof)(property.value)},${property},${len});`;
    }
    validateRegex(eventListener, property) {
        var _a;
        const pattern = (_a = this.schema.pattern) === null || _a === void 0 ? void 0 : _a.replace(/"/g, '""');
        if (!pattern) {
            return '';
        }
        return `await ${eventListener}.AssertRegEx(${(0, codegen_1.nameof)(property.value)}, ${property}, @"${pattern}");`;
    }
    validateEnum(eventListener, property) {
        if (this.schema.type !== codemodel_1.SchemaType.SealedChoice && this.schema.type != codemodel_1.SchemaType.Choice) {
            return '';
        }
        const choiceValues = this.schema.choices.map((c) => c.value);
        return `await ${eventListener}.AssertEnum(${(0, codegen_1.nameof)(property.value)},${property},${choiceValues.joinWith((v) => `@"${v}"`)});`;
    }
}
exports.String = String;
//# sourceMappingURL=string.js.map