'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var coreAuth = require('@azure/core-auth');
var communicationCommon = require('@azure/communication-common');
var coreClient = require('@azure/core-client');
var coreLro = require('@azure/core-lro');
var tslib = require('tslib');
var logger$1 = require('@azure/logger');

function _interopNamespace(e) {
    if (e && e.__esModule) return e;
    var n = Object.create(null);
    if (e) {
        Object.keys(e).forEach(function (k) {
            if (k !== 'default') {
                var d = Object.getOwnPropertyDescriptor(e, k);
                Object.defineProperty(n, k, d.get ? d : {
                    enumerable: true,
                    get: function () { return e[k]; }
                });
            }
        });
    }
    n["default"] = e;
    return Object.freeze(n);
}

var coreClient__namespace = /*#__PURE__*/_interopNamespace(coreClient);

/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */
const EmailSendResult = {
    type: {
        name: "Composite",
        className: "EmailSendResult",
        modelProperties: {
            id: {
                serializedName: "id",
                required: true,
                type: {
                    name: "String"
                }
            },
            status: {
                serializedName: "status",
                required: true,
                type: {
                    name: "String"
                }
            },
            error: {
                serializedName: "error",
                type: {
                    name: "Composite",
                    className: "ErrorDetail"
                }
            }
        }
    }
};
const ErrorDetail = {
    type: {
        name: "Composite",
        className: "ErrorDetail",
        modelProperties: {
            code: {
                serializedName: "code",
                readOnly: true,
                type: {
                    name: "String"
                }
            },
            message: {
                serializedName: "message",
                readOnly: true,
                type: {
                    name: "String"
                }
            },
            target: {
                serializedName: "target",
                readOnly: true,
                type: {
                    name: "String"
                }
            },
            details: {
                serializedName: "details",
                readOnly: true,
                type: {
                    name: "Sequence",
                    element: {
                        type: {
                            name: "Composite",
                            className: "ErrorDetail"
                        }
                    }
                }
            },
            additionalInfo: {
                serializedName: "additionalInfo",
                readOnly: true,
                type: {
                    name: "Sequence",
                    element: {
                        type: {
                            name: "Composite",
                            className: "ErrorAdditionalInfo"
                        }
                    }
                }
            }
        }
    }
};
const ErrorAdditionalInfo = {
    type: {
        name: "Composite",
        className: "ErrorAdditionalInfo",
        modelProperties: {
            type: {
                serializedName: "type",
                readOnly: true,
                type: {
                    name: "String"
                }
            },
            info: {
                serializedName: "info",
                readOnly: true,
                type: {
                    name: "Dictionary",
                    value: { type: { name: "any" } }
                }
            }
        }
    }
};
const ErrorResponse = {
    type: {
        name: "Composite",
        className: "ErrorResponse",
        modelProperties: {
            error: {
                serializedName: "error",
                type: {
                    name: "Composite",
                    className: "ErrorDetail"
                }
            }
        }
    }
};
const EmailMessage = {
    type: {
        name: "Composite",
        className: "EmailMessage",
        modelProperties: {
            headers: {
                serializedName: "headers",
                type: {
                    name: "Dictionary",
                    value: { type: { name: "String" } }
                }
            },
            senderAddress: {
                serializedName: "senderAddress",
                required: true,
                type: {
                    name: "String"
                }
            },
            content: {
                serializedName: "content",
                type: {
                    name: "Composite",
                    className: "EmailContent"
                }
            },
            recipients: {
                serializedName: "recipients",
                type: {
                    name: "Composite",
                    className: "EmailRecipients"
                }
            },
            attachments: {
                serializedName: "attachments",
                type: {
                    name: "Sequence",
                    element: {
                        type: {
                            name: "Composite",
                            className: "EmailAttachment"
                        }
                    }
                }
            },
            replyTo: {
                serializedName: "replyTo",
                type: {
                    name: "Sequence",
                    element: {
                        type: {
                            name: "Composite",
                            className: "EmailAddress"
                        }
                    }
                }
            },
            disableUserEngagementTracking: {
                serializedName: "userEngagementTrackingDisabled",
                type: {
                    name: "Boolean"
                }
            }
        }
    }
};
const EmailContent = {
    type: {
        name: "Composite",
        className: "EmailContent",
        modelProperties: {
            subject: {
                serializedName: "subject",
                required: true,
                type: {
                    name: "String"
                }
            },
            plainText: {
                serializedName: "plainText",
                type: {
                    name: "String"
                }
            },
            html: {
                serializedName: "html",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const EmailRecipients = {
    type: {
        name: "Composite",
        className: "EmailRecipients",
        modelProperties: {
            to: {
                serializedName: "to",
                type: {
                    name: "Sequence",
                    element: {
                        type: {
                            name: "Composite",
                            className: "EmailAddress"
                        }
                    }
                }
            },
            cc: {
                serializedName: "cc",
                type: {
                    name: "Sequence",
                    element: {
                        type: {
                            name: "Composite",
                            className: "EmailAddress"
                        }
                    }
                }
            },
            bcc: {
                serializedName: "bcc",
                type: {
                    name: "Sequence",
                    element: {
                        type: {
                            name: "Composite",
                            className: "EmailAddress"
                        }
                    }
                }
            }
        }
    }
};
const EmailAddress = {
    type: {
        name: "Composite",
        className: "EmailAddress",
        modelProperties: {
            address: {
                serializedName: "address",
                required: true,
                type: {
                    name: "String"
                }
            },
            displayName: {
                serializedName: "displayName",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const EmailAttachment = {
    type: {
        name: "Composite",
        className: "EmailAttachment",
        modelProperties: {
            name: {
                serializedName: "name",
                required: true,
                type: {
                    name: "String"
                }
            },
            contentType: {
                serializedName: "contentType",
                required: true,
                type: {
                    name: "String"
                }
            },
            contentInBase64: {
                serializedName: "contentInBase64",
                required: true,
                type: {
                    name: "String"
                }
            }
        }
    }
};
const EmailGetSendResultHeaders = {
    type: {
        name: "Composite",
        className: "EmailGetSendResultHeaders",
        modelProperties: {
            retryAfter: {
                serializedName: "retry-after",
                type: {
                    name: "Number"
                }
            }
        }
    }
};
const EmailGetSendResultExceptionHeaders = {
    type: {
        name: "Composite",
        className: "EmailGetSendResultExceptionHeaders",
        modelProperties: {
            xMsErrorCode: {
                serializedName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            }
        }
    }
};
const EmailSendHeaders = {
    type: {
        name: "Composite",
        className: "EmailSendHeaders",
        modelProperties: {
            operationLocation: {
                serializedName: "operation-location",
                type: {
                    name: "String"
                }
            },
            retryAfter: {
                serializedName: "retry-after",
                type: {
                    name: "Number"
                }
            }
        }
    }
};
const EmailSendExceptionHeaders = {
    type: {
        name: "Composite",
        className: "EmailSendExceptionHeaders",
        modelProperties: {
            xMsErrorCode: {
                serializedName: "x-ms-error-code",
                type: {
                    name: "String"
                }
            }
        }
    }
};

var Mappers = /*#__PURE__*/Object.freeze({
    __proto__: null,
    EmailSendResult: EmailSendResult,
    ErrorDetail: ErrorDetail,
    ErrorAdditionalInfo: ErrorAdditionalInfo,
    ErrorResponse: ErrorResponse,
    EmailMessage: EmailMessage,
    EmailContent: EmailContent,
    EmailRecipients: EmailRecipients,
    EmailAddress: EmailAddress,
    EmailAttachment: EmailAttachment,
    EmailGetSendResultHeaders: EmailGetSendResultHeaders,
    EmailGetSendResultExceptionHeaders: EmailGetSendResultExceptionHeaders,
    EmailSendHeaders: EmailSendHeaders,
    EmailSendExceptionHeaders: EmailSendExceptionHeaders
});

/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */
const accept = {
    parameterPath: "accept",
    mapper: {
        defaultValue: "application/json",
        isConstant: true,
        serializedName: "Accept",
        type: {
            name: "String"
        }
    }
};
const endpoint = {
    parameterPath: "endpoint",
    mapper: {
        serializedName: "endpoint",
        required: true,
        type: {
            name: "String"
        }
    },
    skipEncoding: true
};
const operationId = {
    parameterPath: "operationId",
    mapper: {
        serializedName: "operationId",
        required: true,
        type: {
            name: "String"
        }
    }
};
const apiVersion = {
    parameterPath: "apiVersion",
    mapper: {
        defaultValue: "2023-03-31",
        isConstant: true,
        serializedName: "api-version",
        type: {
            name: "String"
        }
    }
};
const contentType = {
    parameterPath: ["options", "contentType"],
    mapper: {
        defaultValue: "application/json",
        isConstant: true,
        serializedName: "Content-Type",
        type: {
            name: "String"
        }
    }
};
const message = {
    parameterPath: "message",
    mapper: EmailMessage
};
const operationId1 = {
    parameterPath: ["options", "operationId"],
    mapper: {
        serializedName: "Operation-Id",
        type: {
            name: "Uuid"
        }
    }
};
const clientRequestId = {
    parameterPath: ["options", "clientRequestId"],
    mapper: {
        serializedName: "x-ms-client-request-id",
        type: {
            name: "Uuid"
        }
    }
};

/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */
class LroImpl {
    constructor(sendOperationFn, args, spec, requestPath = spec.path, requestMethod = spec.httpMethod) {
        this.sendOperationFn = sendOperationFn;
        this.args = args;
        this.spec = spec;
        this.requestPath = requestPath;
        this.requestMethod = requestMethod;
    }
    async sendInitialRequest() {
        return this.sendOperationFn(this.args, this.spec);
    }
    async sendPollRequest(path) {
        const _a = this.spec, restSpec = tslib.__rest(_a, ["requestBody"]);
        return this.sendOperationFn(this.args, Object.assign(Object.assign({}, restSpec), { path, httpMethod: "GET" }));
    }
}

/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */
/** Class containing Email operations. */
class EmailImpl {
    /**
     * Initialize a new instance of the class Email class.
     * @param client Reference to the service client
     */
    constructor(client) {
        this.client = client;
    }
    /**
     * Gets the status of the email send operation.
     * @param operationId ID of the long running operation (GUID) returned from a previous call to send
     *                    email
     * @param options The options parameters.
     */
    getSendResult(operationId, options) {
        return this.client.sendOperationRequest({ operationId, options }, getSendResultOperationSpec);
    }
    /**
     * Queues an email message to be sent to one or more recipients
     * @param message Message payload for sending an email
     * @param options The options parameters.
     */
    async beginSend(message, options) {
        const directSendOperation = async (args, spec) => {
            return this.client.sendOperationRequest(args, spec);
        };
        const sendOperation = async (args, spec) => {
            var _a;
            let currentRawResponse = undefined;
            const providedCallback = (_a = args.options) === null || _a === void 0 ? void 0 : _a.onResponse;
            const callback = (rawResponse, flatResponse) => {
                currentRawResponse = rawResponse;
                providedCallback === null || providedCallback === void 0 ? void 0 : providedCallback(rawResponse, flatResponse);
            };
            const updatedArgs = Object.assign(Object.assign({}, args), { options: Object.assign(Object.assign({}, args.options), { onResponse: callback }) });
            const flatResponse = await directSendOperation(updatedArgs, spec);
            return {
                flatResponse,
                rawResponse: {
                    statusCode: currentRawResponse.status,
                    body: currentRawResponse.parsedBody,
                    headers: currentRawResponse.headers.toJSON()
                }
            };
        };
        const lro = new LroImpl(sendOperation, { message, options }, sendOperationSpec);
        const poller = new coreLro.LroEngine(lro, {
            resumeFrom: options === null || options === void 0 ? void 0 : options.resumeFrom,
            intervalInMs: options === null || options === void 0 ? void 0 : options.updateIntervalInMs,
            lroResourceLocationConfig: "azure-async-operation"
        });
        await poller.poll();
        return poller;
    }
    /**
     * Queues an email message to be sent to one or more recipients
     * @param message Message payload for sending an email
     * @param options The options parameters.
     */
    async beginSendAndWait(message, options) {
        const poller = await this.beginSend(message, options);
        return poller.pollUntilDone();
    }
}
// Operation Specifications
const serializer = coreClient__namespace.createSerializer(Mappers, /* isXml */ false);
const getSendResultOperationSpec = {
    path: "/emails/operations/{operationId}",
    httpMethod: "GET",
    responses: {
        200: {
            bodyMapper: EmailSendResult,
            headersMapper: EmailGetSendResultHeaders
        },
        default: {
            bodyMapper: ErrorResponse,
            headersMapper: EmailGetSendResultExceptionHeaders
        }
    },
    queryParameters: [apiVersion],
    urlParameters: [endpoint, operationId],
    headerParameters: [accept],
    serializer
};
const sendOperationSpec = {
    path: "/emails:send",
    httpMethod: "POST",
    responses: {
        200: {
            bodyMapper: EmailSendResult,
            headersMapper: EmailSendHeaders
        },
        201: {
            bodyMapper: EmailSendResult,
            headersMapper: EmailSendHeaders
        },
        202: {
            bodyMapper: EmailSendResult,
            headersMapper: EmailSendHeaders
        },
        204: {
            bodyMapper: EmailSendResult,
            headersMapper: EmailSendHeaders
        },
        default: {
            bodyMapper: ErrorResponse,
            headersMapper: EmailSendExceptionHeaders
        }
    },
    requestBody: message,
    queryParameters: [apiVersion],
    urlParameters: [endpoint],
    headerParameters: [
        accept,
        contentType,
        operationId1,
        clientRequestId
    ],
    mediaType: "json",
    serializer
};

/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */
class EmailRestApiClient extends coreClient__namespace.ServiceClient {
    /**
     * Initializes a new instance of the EmailRestApiClient class.
     * @param endpoint The communication resource, for example https://my-resource.communication.azure.com
     * @param options The parameter options
     */
    constructor(endpoint, options) {
        var _a, _b;
        if (endpoint === undefined) {
            throw new Error("'endpoint' cannot be null");
        }
        // Initializing default values for options
        if (!options) {
            options = {};
        }
        const defaults = {
            requestContentType: "application/json; charset=utf-8"
        };
        const packageDetails = `azsdk-js-communication-email/1.0.0`;
        const userAgentPrefix = options.userAgentOptions && options.userAgentOptions.userAgentPrefix
            ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
            : `${packageDetails}`;
        const optionsWithDefaults = Object.assign(Object.assign(Object.assign({}, defaults), options), { userAgentOptions: {
                userAgentPrefix
            }, baseUri: (_b = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri) !== null && _b !== void 0 ? _b : "{endpoint}" });
        super(optionsWithDefaults);
        // Parameter assignments
        this.endpoint = endpoint;
        // Assigning values to Constant parameters
        this.apiVersion = options.apiVersion || "2023-03-31";
        this.email = new EmailImpl(this);
        this.addCustomApiVersionPolicy(options.apiVersion);
    }
    /** A function that adds a policy that sets the api-version (or equivalent) to reflect the library version. */
    addCustomApiVersionPolicy(apiVersion) {
        if (!apiVersion) {
            return;
        }
        const apiVersionPolicy = {
            name: "CustomApiVersionPolicy",
            async sendRequest(request, next) {
                const param = request.url.split("?");
                if (param.length > 1) {
                    const newParams = param[1].split("&").map((item) => {
                        if (item.indexOf("api-version") > -1) {
                            return "api-version=" + apiVersion;
                        }
                        else {
                            return item;
                        }
                    });
                    request.url = param[0] + "?" + newParams.join("&");
                }
                return next(request);
            }
        };
        this.pipeline.addPolicy(apiVersionPolicy);
    }
}

// Copyright (c) Microsoft Corporation.
/**
 * The \@azure/logger configuration for this package.
 */
const logger = logger$1.createClientLogger("communication-email");

// Copyright (c) Microsoft Corporation.
/**
 * Checks whether the type of a value is EmailClientOptions or not.
 *
 * @param options - The value being checked.
 */
const isEmailClientOptions = (options) => !!options && !coreAuth.isTokenCredential(options) && !communicationCommon.isKeyCredential(options);
/**
 *  The Email service client.
 */
class EmailClient {
    constructor(connectionStringOrUrl, credentialOrOptions, maybeOptions = {}) {
        const { url, credential } = communicationCommon.parseClientArguments(connectionStringOrUrl, credentialOrOptions);
        const options = isEmailClientOptions(credentialOrOptions) ? credentialOrOptions : maybeOptions;
        const internalPipelineOptions = Object.assign(Object.assign({}, options), {
            loggingOptions: {
                logger: logger.info,
            },
        });
        const authPolicy = communicationCommon.createCommunicationAuthPolicy(credential);
        this.generatedClient = new EmailRestApiClient(url, internalPipelineOptions);
        this.generatedClient.pipeline.addPolicy(authPolicy);
    }
    /**
     * Queues an email message to be sent to one or more recipients
     * @param message - Message payload for sending an email
     * @param options - The options parameters.
     */
    beginSend(message, options) {
        return this.generatedClient.email.beginSend(message, options);
    }
}

/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT License.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is regenerated.
 */
/** Known values of {@link EmailSendStatus} that the service accepts. */
exports.KnownEmailSendStatus = void 0;
(function (KnownEmailSendStatus) {
    /** NotStarted */
    KnownEmailSendStatus["NotStarted"] = "NotStarted";
    /** Running */
    KnownEmailSendStatus["Running"] = "Running";
    /** Succeeded */
    KnownEmailSendStatus["Succeeded"] = "Succeeded";
    /** Failed */
    KnownEmailSendStatus["Failed"] = "Failed";
    /** Canceled */
    KnownEmailSendStatus["Canceled"] = "Canceled";
})(exports.KnownEmailSendStatus || (exports.KnownEmailSendStatus = {}));

exports.EmailClient = EmailClient;
//# sourceMappingURL=index.js.map
