import w from"stringify-object";import{CodeBuilder as A}from"../../helpers/code-builder.js";import{HTTPSnippet as S}from"../../index.js";import{addIndentation as E,buildUrlExpression as O,printUrlVariablesDeclarations as v}from"../../helpers/code-helpers.js";import{normalizeMimeType as h}from"../../../../utils.js";import{capitalizeFirst as x}from"../../../generator.js";import{Lang as k}from"../../helpers/constants.js";import{MediaTypes as s}from"../../../../../constants.js";import{buildCSharpNewtonsoftDeviceAuthorizationCodeSnippet as R}from"../../helpers/device-auth-snippets.js";const M=function(e,c,{target:g,client:C}){const i=Object.assign({indent:"  ",withWrapper:!0},c),t=new A({indentation:i.indent,variablesPrefix:i.variablesPrefix,capitalize:!0,lang:k.CSHARPNEWTONSOFT}),y=H(e.method);if(i.withComments&&N(t),i.withWrapper&&(t.push("using System;"),t.push("using System.Net.Http;"),t.push("using System.Threading.Tasks;"),(o(s.JSON)||o(s.XML)||e.basicAuth)&&t.push("using System.Text;"),(o(s.URL_ENCODED)||e.securityOAuth2ExtraCalls?.length)&&t.push("using System.Collections.Generic;"),(o(s.JSON)||e.securityOAuth2ExtraCalls?.length)&&t.push("using Newtonsoft.Json.Linq;"),(r()||!e.postData?.params?.length&&e.postData?.text&&h(e.postData.mimeType)===s.MULTIPART)&&t.push("using System.IO;"),(r()||e.basicAuth)&&t.push("using System.Net.Http.Headers;"),t.blank(),t.push("public class Program"),t.push("{"),t.push(1,"private readonly IHttpClientFactory _httpClientFactory;"),t.push(1,"public static async Task Main(string[] args)"),t.push(1,"{"),t.push(2,"var client = _httpClientFactory.CreateClient();")),e.securityOAuth2ExtraCalls?.length){const a=e.securityOAuth2ExtraCalls?.[0],n=new S(a).convert(g,C,{...i,withImports:!1,withWrapper:!1,withComments:!1,variablesPrefix:"oauth2"});t.push(n),t.push(2,"var oauth2Response = await oauth2Request.Content.ReadAsStringAsync();"),a.flowType==="deviceAuthorization"?R(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&&d.forEach(a=>{const n=a.toLowerCase()==="authorization";t.push(2,'client.DefaultRequestHeaders.Add("%s", %s);',a,e.securityOAuth2ExtraCalls?.length&&n?'"Bearer " + accessToken':`"${e.allHeaders[a]}"`)}),e.basicAuth){const{username:a,password:n}=e.basicAuth;t.push(2,`var base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes("${a}:${n}"));`),t.push(2,'client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(@"Basic", base64String);')}if(e.postData)switch(h(e.postData.mimeType)){case s.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 s.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,n=a.match(/^--([^\r\n]+)/);if(n){const p=n[1],T=a.split(new RegExp(`--${p.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?:--)?`,"g")).filter(l=>l.trim().length>0);t.blank(),t.push(2,"MultipartFormDataContent postData = new MultipartFormDataContent();"),T.forEach(l=>{const u=l.match(/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;\s*filename="([^"]+)")?/i);if(u){const f=u[1],m=u[2],D=l.match(/\r?\n\r?\n([\s\S]*?)(?:\r?\n)?$/),b=(D?D[1].trim():"").replace(/\\/g,"\\\\").replace(/"/g,'\\"');m?t.push(2,'postData.Add(new ByteArrayContent(File.ReadAllBytes("%s")), "%s", "%s");',m,f,m):t.push(2,'postData.Add(new StringContent("%s"), "%s");',b,f)}})}else{t.blank();const p=e.postData.text.replace(/\\/g,"\\\\").replace(/"/g,'\\"');t.push(2,'var postData = new StringContent("%s");',p)}}break;case s.JSON:e.postData.jsonObj&&(t.push(2,`JObject json = JObject.Parse(@"${E(w(e.postData.jsonObj,{indent:i.indent,inlineCharacterLimit:25}).replace(/"/g,'""'),{level:3,firstLine:!1})}");`),t.push(2,'var postData = new StringContent(json.ToString(), Encoding.UTF8, "%s");',e.postData.mimeType));break;case s.XML:e.postData.text&&(e.postData.text.trim().split(`
`).forEach((a,n)=>{const p=(n===0?'string xml = @"':"")+a.replace(/"/g,'""');t.push(n===0?3:4,p)}),t.push(2,'";'),t.push(2,'var postData = new StringContent(xml, Encoding.UTF8, "%s");',e.postData.mimeType));break;case s.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 r()&&(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 v(e,t,3),t.push(2,"var %s = await client.%sAsync(%s%s);",t.var("request"),y,O(e,t),i.withImports?L(e.method)?h(e.postData&&e.postData.mimeType)===s.URL_ENCODED?", new FormUrlEncodedContent(postData)":e.method==="delete"?"":e.postData&&e.postData.params||r()?", postData":", null":"":", new FormUrlEncodedContent(postData)"),i.withWrapper&&(t.push(2,"var response = await request.Content.ReadAsStringAsync();"),t.blank(),t.push(2,"Console.WriteLine(response);"),t.push(1,"}"),t.push("}")),t.join();function o(a){return e.postData&&h(e.postData.mimeType)===a}function r(){return e.headersObj&&e.headersObj["Content-Type"]===s.OCTET_STREAM}},$={key:"httpclient",title:"HttpClient",link:"https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient",description:".NET Standard HTTP Client"};var z=M;function N(e){e.push("/*"),e.push(" * Requires >= .NET 5"),e.push(" *"),e.push(' * Requires package "Newtonsoft.Json" >= 9.01'),e.push(" * See here for installation details:"),e.push(" *  https://www.newtonsoft.com/json"),e.push(" */"),e.blank()}function H(e){return x(e.toLowerCase())}function L(e){return e&&["POST","PUT","DELETE","PATCH"].includes(e.toUpperCase())}export{z as default,$ as info};
