"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SimpleServiceRequestBase = void 0;
const TraceFlags_1 = require("../../Enumerations/TraceFlags");
const RenderingMode_1 = require("../../Enumerations/RenderingMode");
const ServiceRequestException_1 = require("../../Exceptions/ServiceRequestException");
const Strings_1 = require("../../Strings");
const EwsServiceXmlReader_1 = require("../EwsServiceXmlReader");
const EwsLogging_1 = require("../EwsLogging");
const ExtensionMethods_1 = require("../../ExtensionMethods");
const ServiceRequestBase_1 = require("./ServiceRequestBase");
const SoapFaultDetails_1 = require("../../Misc/SoapFaultDetails");
const Exception_1 = require("../../Exceptions/Exception");
/** @internal */
class SimpleServiceRequestBase extends ServiceRequestBase_1.ServiceRequestBase {
    //BeginExecute(callback: System.AsyncCallback, state: any): any/*System.IAsyncResult*/ { throw new Error("SimpleServiceRequestBase.ts - BeginExecute : Not implemented.");}
    //EndInternalExecute(asyncResult: any/*System.IAsyncResult*/): any { throw new Error("SimpleServiceRequestBase.ts - EndInternalExecute : Not implemented.");}
    InternalExecute() {
        //var writer = new Data.EwsServiceXmlWriter();
        //this.WriteSoapRequest(this.url, writer);
        //if (!this.Service && !this.Service.Credentials && (!this.Service.Credentials.UserName || this.service.Credentials.Password))
        //    throw new Error("missing credential");
        //var cred = "Basic " + btoa(this.Service.Credentials.UserName + ":" + this.Service.Credentials.Password);
        //var cc = writer.GetXML();
        //var xhrOptions: IXHROptions = {
        //    type: "POST",
        //    data: cc,
        //    url: "https://pod51045.outlook.com/autodiscover/autodiscover.svc",
        //    headers: { "Content-Type": "text/xml", "Authorization": cred },
        //    //customRequestInitializer: function (x) {
        //    //    var m = x;
        //    //}
        //};
        return new Promise((successDelegate, errorDelegate) => {
            var request = this.BuildXHR();
            //this.ReadResponsePrivate(response);
            this.ValidateAndEmitRequest(request).then((xhrResponse) => {
                var dom = new ExtensionMethods_1.DOMParser();
                var xml2js = new ExtensionMethods_1.xml2JsObject();
                var req = xml2js.parseXMLNode(dom.parseFromString(request.data, "text/xml").documentElement, true);
                EwsLogging_1.EwsLogging.DebugLog(req, true);
                if (xhrResponse.status == 200) {
                    EwsLogging_1.EwsLogging.DebugLog(xhrResponse, true);
                    try {
                        var ewsXmlReader = new EwsServiceXmlReader_1.EwsServiceXmlReader(xhrResponse.responseText || xhrResponse.response, this.Service);
                        //EwsLogging.DebugLog(ewsXmlReader.JsObject, true);
                        var serviceResponse = this.ReadResponsePrivate(xhrResponse, ewsXmlReader.JsObject);
                        if (successDelegate)
                            successDelegate(serviceResponse || xhrResponse.responseText || xhrResponse.response);
                    }
                    catch (err) {
                        if (err instanceof Exception_1.Exception)
                            errorDelegate(err);
                        else
                            errorDelegate(new SoapFaultDetails_1.SoapFaultDetails(err.message));
                    }
                }
                else {
                    if (errorDelegate)
                        errorDelegate(this.ProcessWebException(xhrResponse) || xhrResponse);
                }
            }, (resperr) => {
                EwsLogging_1.EwsLogging.Log("Error in calling service, error code:" + resperr.status + "\r\n" + ((resperr.getAllResponseHeaders) ? resperr.getAllResponseHeaders() : ""));
                if (errorDelegate)
                    errorDelegate(this.ProcessWebException(resperr) || resperr);
            });
        });
    }
    ReadResponsePrivate(response /*IEwsHttpWebResponse*/, jsObject) {
        var serviceResponse;
        try {
            this.Service.ProcessHttpResponseHeaders(TraceFlags_1.TraceFlags.EwsResponseHttpHeaders, response);
            // If tracing is enabled, we read the entire response into a MemoryStream so that we
            // can pass it along to the ITraceListener. Then we parse the response from the
            // MemoryStream.
            if (this.Service.IsTraceEnabledFor(TraceFlags_1.TraceFlags.EwsResponse)) { //todo: implement tracing
                //using(MemoryStream memoryStream = new MemoryStream())
                //{
                //    using(Stream serviceResponseStream = ServiceRequestBase.GetResponseStream(response))
                //    {
                //        // Copy response to in-memory stream and reset position to start.
                //        EwsUtilities.CopyStream(serviceResponseStream, memoryStream);
                //        memoryStream.Position = 0;
                //    }
                //    if (this.Service.RenderingMethod == ExchangeService.RenderingMode.Xml) {
                //        this.TraceResponseXml(response, memoryStream);
                //        serviceResponse = this.ReadResponseXml(memoryStream);
                //    }
                //    else if (this.Service.RenderingMethod == ExchangeService.RenderingMode.JSON) {
                //        this.TraceResponseJson(response, memoryStream);
                //        serviceResponse = this.ReadResponseJson(memoryStream);
                //    }
                //    else {
                //        throw new InvalidOperationException("Unknown RenderingMethod.");
                //    }
                //}
            }
            else {
                if (this.Service.RenderingMethod == RenderingMode_1.RenderingMode.Xml) {
                    serviceResponse = this.ReadResponseXmlJsObject(jsObject);
                }
                else if (this.Service.RenderingMethod == RenderingMode_1.RenderingMode.JSON) {
                    serviceResponse = this.ReadResponseJson(jsObject);
                }
                else {
                    throw new Error /*InvalidOperationException*/("Unknown RenderingMethod.");
                }
            }
        }
        catch (ex) {
            if (ex.Response != null) {
                //IEwsHttpWebResponse exceptionResponse = this.Service.HttpWebRequestFactory.CreateExceptionResponse(e);
                this.Service.ProcessHttpResponseHeaders(TraceFlags_1.TraceFlags.EwsResponseHttpHeaders, response);
            }
            throw new ServiceRequestException_1.ServiceRequestException(ExtensionMethods_1.StringHelper.Format(Strings_1.Strings.ServiceRequestFailed, ex.message /* ex can be generic Error*/), ex);
        }
        return serviceResponse;
    }
    ReadResponseJson(jsObject /*System.IO.Stream*/) {
        //var jsonResponse: JsonObject = new JsonParser(responseStream).Parse();
        return super.BuildResponseObjectFromJson(jsObject);
    }
    WebRequestAsyncCallback(webAsyncResult /*System.IAsyncResult*/) { throw new Error("SimpleServiceRequestBase.ts - WebRequestAsyncCallback : Not implemented."); }
}
exports.SimpleServiceRequestBase = SimpleServiceRequestBase;
//# sourceMappingURL=SimpleServiceRequestBase.js.map