1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
use crate::{
  pkg::{
    data_format_elems::DataFormatElems,
    fir::{
      fir_after_sending_item_values::FirAfterSendingItemValues,
      fir_aux_item_values::FirAuxItemValues,
      fir_before_sending_item_values::FirBeforeSendingItemValues,
      fir_params_items_values::FirParamsItemValues, fir_req_item_values::FirReqItemValues,
      fir_res_item_values::FirResItemValues,
    },
    misc::split_params,
    sir::{sir_aux_item_values::SirAuxItemValues, sir_pkg_attr::SirPkaAttr},
  },
  transport_group::TransportGroup,
};
use proc_macro2::{Ident, Span, TokenStream};
use syn::GenericParam;

pub(crate) struct SirFinalValues {
  pub(crate) auxs: Vec<TokenStream>,
  pub(crate) package: TokenStream,
  pub(crate) package_impls: Vec<TokenStream>,
}

impl SirFinalValues {
  fn pkg_params<'any>(
    freqdiv: &'any FirReqItemValues<'any>,
    fpiv: &'any FirParamsItemValues<'any>,
  ) -> (impl Iterator<Item = &'any GenericParam>, impl Iterator<Item = &'any GenericParam>) {
    let (a_lts, a_tys) = split_params(fpiv.fpiv_params);
    let (b_lts, b_tys) = split_params(freqdiv.freqdiv_params);
    (a_lts.chain(b_lts), a_tys.chain(b_tys))
  }
  fn transport_params(transport_group: &TransportGroup) -> TokenStream {
    match *transport_group {
      TransportGroup::Custom(ref tt) => {
        quote::quote!(<#tt as lucia::network::transport::Transport<DRSR>>::Params)
      }
      TransportGroup::Http => quote::quote!(lucia::network::HttpParams),
      TransportGroup::Stub => quote::quote!(()),
      TransportGroup::Tcp => quote::quote!(lucia::network::TcpParams),
      TransportGroup::Udp => quote::quote!(lucia::network::UdpParams),
      TransportGroup::WebSocket => quote::quote!(lucia::network::WsParams),
    }
  }
}

impl<'attrs, 'module, 'others>
  TryFrom<(
    &'others mut String,
    FirParamsItemValues<'module>,
    FirReqItemValues<'module>,
    FirResItemValues<'others>,
    SirPkaAttr<'attrs>,
    Option<FirAfterSendingItemValues<'module>>,
    Option<FirAuxItemValues<'module>>,
    Option<FirBeforeSendingItemValues<'module>>,
  )> for SirFinalValues
{
  type Error = crate::Error;

  fn try_from(
    (camel_case_id, fpiv, freqdiv, fresdiv, spa, fasiv_opt, faiv_opt, fbsiv_opt): (
      &'others mut String,
      FirParamsItemValues<'module>,
      FirReqItemValues<'module>,
      FirResItemValues<'others>,
      SirPkaAttr<'attrs>,
      Option<FirAfterSendingItemValues<'module>>,
      Option<FirAuxItemValues<'module>>,
      Option<FirBeforeSendingItemValues<'module>>,
    ),
  ) -> Result<Self, Self::Error> {
    let FirParamsItemValues { ref fpiv_ty, fpiv_params, fpiv_where_predicates, .. } = fpiv;
    let FirReqItemValues { freqdiv_ident, freqdiv_params, freqdiv_where_predicates, .. } = freqdiv;
    let FirResItemValues { res_ident } = fresdiv;
    let SirPkaAttr { api, ref data_formats, ref error, ref transport_groups } = spa;
    let camel_case_pkg_ident = &{
      let idx = camel_case_id.len();
      camel_case_id.push_str("Pkg");
      let ident = Ident::new(camel_case_id, Span::mixed_site());
      camel_case_id.truncate(idx);
      ident
    };

    let fasiv_fn_call_idents = fasiv_opt.as_ref().map(|el| &el.fasiv_fn_call_idents);
    let fbsiv_fn_call_idents = fbsiv_opt.as_ref().map(|el| &el.fbsiv_fn_call_idents);
    let saiv_tts = faiv_opt
      .as_ref()
      .map(|elem| {
        SirAuxItemValues::try_from((
          camel_case_id,
          camel_case_pkg_ident,
          elem,
          &fpiv,
          &freqdiv,
          &spa,
        ))
      })
      .transpose()?
      .map(|elem| elem.saiv_tts)
      .unwrap_or_default();
    let mut package_impls = Vec::new();

    for data_format in data_formats {
      let DataFormatElems { dfe_ext_req_ctnt_wrapper, dfe_ext_res_ctnt_wrapper, .. } =
        data_format.elems();
      for transport_group in transport_groups {
        let before_sending_defaults = data_format.before_sending_defaults(transport_group);
        let fasiv_fn_name_ident_iter =
          fasiv_opt.as_ref().map(|el| &el.fasiv_item.sig.ident).into_iter();
        let fbsiv_fn_name_ident_iter =
          fbsiv_opt.as_ref().map(|el| &el.fbsiv_item.sig.ident).into_iter();
        let fpiv_params_iter = fpiv_params.iter();
        let fpiv_where_predicates_iter = fpiv_where_predicates.iter();
        let freqdiv_where_predicates_iter = freqdiv_where_predicates.iter();
        let tp = Self::transport_params(transport_group);
        let (lts, tys) = Self::pkg_params(&freqdiv, &fpiv);
        #[cfg(feature = "async-trait")]
        let async_trait_cfg = quote::quote!(#[async_trait::async_trait]);
        #[cfg(not(feature = "async-trait"))]
        let async_trait_cfg = TokenStream::new();
        package_impls.push(quote::quote!(
          #async_trait_cfg
          impl<
            #(#lts,)*
            #(#tys,)*
            DRSR
          > lucia::pkg::Package<DRSR, #tp> for #camel_case_pkg_ident<
            #(#fpiv_params_iter,)*
            lucia::data_format::#dfe_ext_req_ctnt_wrapper<#freqdiv_ident<#freqdiv_params>>
          >
          where
            #(#fpiv_where_predicates_iter,)*
            #(#freqdiv_where_predicates_iter,)*
            lucia::data_format::#dfe_ext_req_ctnt_wrapper<
              #freqdiv_ident<#freqdiv_params>
            >: lucia::dnsn::Serialize<DRSR>,
            lucia::data_format::#dfe_ext_res_ctnt_wrapper<
              #res_ident
            >: lucia::dnsn::Deserialize<DRSR>,
            DRSR: Send + Sync,
          {
            type Api = #api;
            type Error = #error;
            type ExternalRequestContent = lucia::data_format::#dfe_ext_req_ctnt_wrapper<
              #freqdiv_ident<#freqdiv_params>
            >;
            type ExternalResponseContent = lucia::data_format::#dfe_ext_res_ctnt_wrapper<
              #res_ident
            >;
            type PackageParams = #fpiv_ty;

            async fn after_sending(
              &mut self,
              _api: &mut Self::Api,
              _ext_res_params: &mut <#tp as lucia::network::transport::TransportParams>::ExternalResponseParams,
            ) -> Result<(), Self::Error> {
              #( #fasiv_fn_name_ident_iter(#fasiv_fn_call_idents).await?; )*
              Ok(())
            }

            async fn before_sending(
              &mut self,
              _api: &mut Self::Api,
              _ext_req_params: &mut <#tp as lucia::network::transport::TransportParams>::ExternalRequestParams,
              _req_bytes: &[u8],
            ) -> Result<(), Self::Error> {
              #before_sending_defaults
              #( #fbsiv_fn_name_ident_iter(#fbsiv_fn_call_idents).await?; )*
              Ok(())
            }

            fn ext_req_content(&self) -> &Self::ExternalRequestContent {
              &self.content
            }

            fn ext_req_content_mut(&mut self) -> &mut Self::ExternalRequestContent {
              &mut self.content
            }

            fn pkg_params(&self) -> &Self::PackageParams {
              &self.params
            }

            fn pkg_params_mut(&mut self) -> &mut Self::PackageParams {
              &mut self.params
            }
          }
        ));
      }
    }

    let fpiv_params_iter = fpiv_params.iter();
    Ok(Self {
      auxs: saiv_tts,
      package: quote::quote!(
        /// Package containing all the expected parameters and data necessary to manage and issue
        /// a request.
        ///
        /// For more information, please see the official API's documentation.
        #[derive(Debug)]
        pub struct #camel_case_pkg_ident<#(#fpiv_params_iter,)* C>
        where
          #fpiv_where_predicates
        {
          content: C,
          params: #fpiv_ty,
        }
      ),
      package_impls,
    })
  }
}