import{isObject as T}from"@redocly/theme/core/openapi";import{CodeBuilder as E}from"../../helpers/code-builder.js";import{HTTPSnippet as O}from"../../index.js";import{buildUrlExpression as x,printUrlVariablesDeclarations as k}from"../../helpers/code-helpers.js";import{isEmptyObject as H,normalizeMimeType as m}from"../../../../utils.js";import{capitalizeFirst as v}from"../../../generator.js";import{Lang as M}from"../../helpers/constants.js";import{MediaTypes as i}from"../../../../../constants.js";import{isLastInArray as R,isLastProperty as L}from"../../../../../utils/index.js";import{buildCSharpDeviceAuthorizationCodeSnippet as j}from"../../helpers/device-auth-snippets.js";const N=function(e,d,{target:b,client:w}){const r=Object.assign({indent:"  ",withWrapper:!0},d),t=new E({indentation:r.indent,variablesPrefix:r.variablesPrefix,capitalize:!0,lang:M.CSHARP}),A=U(e.method);if(r.withComments&&P(t),r.withWrapper&&(t.push("using System;"),t.push("using System.Net.Http;"),t.push("using System.Threading.Tasks;"),(h(i.JSON)||h(i.XML)||e.basicAuth)&&t.push("using System.Text;"),(h(i.URL_ENCODED)||e.securityOAuth2ExtraCalls?.length)&&t.push("using System.Collections.Generic;"),(h(i.JSON)||e.securityOAuth2ExtraCalls?.length)&&t.push("using System.Text.Json;"),(u()||!e.postData?.params?.length&&e.postData?.text&&m(e.postData.mimeType)===i.MULTIPART)&&t.push("using System.IO;"),(u()||e.basicAuth)&&t.push("using System.Net.Http.Headers;"),t.blank(),t.push("public class Program"),t.push("{"),t.push(1,"public static async Task Main()"),t.push(1,"{")),e.securityOAuth2ExtraCalls?.length){const a=e.securityOAuth2ExtraCalls?.[0],s=new O(a).convert(b,w,{...r,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});t.push(s),t.push(2,"var oauth2Response = await oauth2Request.Content.ReadAsStringAsync();"),a.flowType==="deviceAuthorization"?j(t,{tokenUrl:a.tokenUrl??"YOUR_TOKEN_URL",clientId:a.clientId??"YOUR_CLIENT_ID",level:2}):(t.push(2,"JObject inputJObject = JObject.Parse(oauth2Response);"),t.push(2,'var accessToken = inputJObject["access_token"].ToString();'),t.blank())}const D=Object.keys(e.allHeaders).filter(a=>{switch(a.toLowerCase()){case"content-type":case"content-length":case"accept-encoding":return!1;default:return!0}});if(D.length?(t.push(2,"System.Net.Http.HttpClient client = new()"),t.push(2,"{"),t.push(3,"DefaultRequestHeaders ="),t.push(3,"{"),D.forEach(a=>{const s=a.toLowerCase()==="authorization";t.push(4,'{"%s", %s},',a,e.securityOAuth2ExtraCalls?.length&&s?'"Bearer " + accessToken':`"${e.allHeaders[a]}"`)}),t.push(3,"}"),t.push(2,"};")):t.push(2,"System.Net.Http.HttpClient client = new();"),t.blank(),e.basicAuth){const{username:a,password:s}=e.basicAuth;t.push(2,`string base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes("${a}:${s}"));`),t.push(2,'client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(@"Basic", base64String);'),t.blank()}if(e.postData)switch(m(e.postData.mimeType)){case i.URL_ENCODED:e.postData.params.length?(t.blank(),t.push(2,"List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>();"),e.postData.params.forEach(a=>{t.push(2,'postData.Add(new KeyValuePair<string, string>("%s", "%s"));',a.name,a.value)}),t.blank()):e.postData.text&&(t.blank(),t.push(3,'var postData = "%s";',e.postData.text));break;case i.MULTIPART:if(e.postData.params&&e.postData.params.length>0)t.blank(),t.push(2,"MultipartFormDataContent postData = new MultipartFormDataContent();"),e.postData.params.forEach(a=>{a.fileName?t.push(2,'postData.Add(new ByteArrayContent(File.ReadAllBytes("%s")), "%s", "%s");',a.fileName,a.name,a.fileName):t.push(2,'postData.Add(new StringContent("%s"), "%s");',a.value,a.name)});else if(e.postData.text){const a=e.postData.text,s=a.match(/^--([^\r\n]+)/);if(s){const n=s[1],p=a.split(new RegExp(`--${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:--)?`,"g")).filter(o=>o.trim().length>0);t.blank(),t.push(2,"MultipartFormDataContent postData = new MultipartFormDataContent();"),p.forEach(o=>{const l=o.match(/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;\s*filename="([^"]+)")?/i);if(l){const g=l[1],f=l[2],C=o.match(/\r?\n\r?\n([\s\S]*?)(?:\r?\n)?$/),S=(C?C[1].trim():"").replace(/\\/g,"\\\\").replace(/"/g,'\\"');f?t.push(2,'postData.Add(new ByteArrayContent(File.ReadAllBytes("%s")), "%s", "%s");',f,g,f):t.push(2,'postData.Add(new StringContent("%s"), "%s");',S,g)}})}else{t.blank();const n=e.postData.text.replace(/\\/g,"\\\\").replace(/"/g,'\\"');t.push(2,'var postData = new StringContent("%s");',n)}}break;case i.JSON:e.postData.jsonObj&&(t.push(2,"string json = JsonSerializer.Serialize(new"),t.push(2,"{"),c(e.postData.jsonObj,3),t.push(2,"});"),t.blank(),t.push(2,'using StringContent postData = new(json, Encoding.UTF8, "%s");',e.postData.mimeType));break;case i.XML:e.postData.text&&(e.postData.text.trim().split(`
`).forEach((a,s)=>{const n=(s===0?'string xml = @"':"")+a.replace(/"/g,'""');t.push(s===0?2:3,n)}),t.push(2,'";'),t.push(2,'using StringContent postData = new StringContent(xml, Encoding.UTF8, "%s");',e.postData.mimeType));break;case i.OCTET_STREAM:e.postData.text&&(t.push(2,'byte[] bytes = Convert.FromBase64String("%s");',e.postData.text),t.push(2,"var postData = new ByteArrayContent(bytes);"),t.push(2,'postData.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");'));break}else u()&&(t.push(2,"var ms = new MemoryStream();"),t.push(2,"var postData = new StreamContent(ms);"),t.push(2,'postData.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");'));return k(e,t,3),t.push(2,"using HttpResponseMessage %s = await client.%sAsync(%s%s);",t.var("request"),A,x(e,t),r.withImports?F(e.method)?m(e.postData&&e.postData.mimeType)===i.URL_ENCODED?", new FormUrlEncodedContent(postData)":e.method==="delete"?"":e.postData&&e.postData.params||u()?", postData":", null":"":", new FormUrlEncodedContent(postData)"),r.withWrapper&&(t.push(2,"string response = await request.Content.ReadAsStringAsync();"),t.blank(),t.push(2,"Console.WriteLine(response);"),t.push(1,"}"),t.push("}")),t.join();function h(a){return e.postData&&m(e.postData.mimeType)===a}function u(){return e.headersObj&&e.headersObj["Content-Type"]===i.OCTET_STREAM}function y(a,s){a.forEach((n,p)=>{const o=!R(a,p);Array.isArray(n)?y(n,s+1):T(n)?(t.push(s+1,"new {"),c(n,s+2),t.push(s+1,"}%s",o?",":"")):t.push(s+1,'"%s"%s',n,o?",":"")}),t.push(s,"},")}function c(a,s){for(const[n,p]of Object.entries(a)){const o=!L(a,n);if(Array.isArray(p))t.push(s,"%s = new[] {",n),y(p,s);else if(T(p)){const l=H(p);t.push(s,"%s = new %s",n,l?"{},":"{"),l||(c(p,s+1),t.push(s,"}%s",o?",":""))}else t.push(s,'%s = "%s"%s',n,p,o?",":"")}}},X={key:"httpclient",title:"HttpClient",link:"https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient",description:".NET Standard HTTP Client"};var Y=N;function P(e){e.push("// Requires >= .NET 5"),e.blank()}function U(e){return v(e.toLowerCase())}function F(e){return e&&["POST","PUT","DELETE","PATCH"].includes(e.toUpperCase())}export{Y as default,X as info};
