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
use crate::sdk::error::SDKError;
use reqwest_middleware::RequestBuilder;
use serde::de::DeserializeOwned;
use serde_repr::{Deserialize_repr, Serialize_repr};
use std::fmt::{Display, Formatter};

pub mod authentication;
pub mod batch;
pub mod client;
pub mod error;
pub mod logging;
pub mod options;
pub mod retry_strategy;

pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const MAX_BATCH_SIZE: usize = 100;

#[derive(Default, Debug, Clone, PartialEq, Serialize_repr, Deserialize_repr)]
#[repr(u8)]
pub enum CoordinateLicense {
    #[default]
    CoordinateLicenseSmartyStreets = 0,
    CoordinateLicenseSmartyStreetsProprietary = 1,
}

impl Display for CoordinateLicense {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            CoordinateLicense::CoordinateLicenseSmartyStreets => {
                write!(f, "SmartyStreets")
            }
            CoordinateLicense::CoordinateLicenseSmartyStreetsProprietary => {
                write!(f, "SmartyStreets Proprietary")
            }
        }
    }
}

pub(crate) async fn send_request<C>(request: RequestBuilder) -> Result<C, SDKError>
where
    C: DeserializeOwned,
{
    let response = match request.send().await {
        Ok(response) => response,
        Err(error) => {
            return Err(SDKError {
                code: None,
                detail: Some(format!("{:?}", error)),
            });
        }
    };

    if !response.status().is_success() {
        let status_code = response.status();
        let body = match response.text().await {
            Ok(body) => body,
            Err(_) => "Could not read body for response".to_string(),
        };

        return Err(SDKError {
            code: Some(status_code.as_u16()),
            detail: Some(body),
        });
    }

    match response.json::<C>().await {
        Ok(candidates) => Ok(candidates),
        Err(err) => Err(SDKError {
            code: None,
            detail: Some(format!("{:?}", err)),
        }),
    }
}

/// This is only used for Serializing for post
#[allow(clippy::trivially_copy_pass_by_ref)]
pub(crate) fn is_zero(num: &i64) -> bool {
    *num == 0
}

pub(crate) fn has_param(name: String, param: String) -> Option<(String, String)> {
    if param != String::default() {
        Some((name, param))
    } else {
        None
    }
}

pub(crate) fn has_i32_param(name: String, param: i32, default: i32) -> Option<(String, String)> {
    if param == default {
        None
    } else {
        Some((name, param.to_string()))
    }
}

pub(crate) fn has_f64_param(name: String, param: f64, default: f64) -> Option<(String, String)> {
    if param == default {
        None
    } else {
        Some((name, param.to_string()))
    }
}

pub(crate) fn has_bool_param(name: String, param: bool, default: bool) -> Option<(String, String)> {
    if param == default {
        None
    } else {
        Some((name, param.to_string()))
    }
}

pub(crate) fn has_vec_param(name: String, param: Vec<String>) -> Option<(String, String)> {
    if !param.is_empty() {
        Some((name, format!("[{}]", param.join(","))))
    } else {
        None
    }
}

// Tests
#[cfg(test)]
mod tests {
    use crate::sdk::authentication::SecretKeyCredential;
    use crate::sdk::batch::Batch;
    use crate::sdk::client::Client;
    use crate::sdk::options::OptionsBuilder;

    #[test]
    fn batch_test() {
        let lookup = "Hello World".to_string();
        let mut batch = Batch::default();
        batch.push(lookup).unwrap();

        assert_eq!(batch.len(), 1);
        assert_eq!(batch.records()[0], "Hello World".to_string())
    }

    #[test]
    fn authentication_test() {
        let authentication = SecretKeyCredential::new("1234".to_string(), "ABCD".to_string());

        assert_eq!(authentication.auth_id, "1234".to_string());
        assert_eq!(authentication.auth_token, "ABCD".to_string());
    }

    #[test]
    fn client_test() {
        let client = Client::new(
            "https://www.smarty.com".parse().unwrap(),
            OptionsBuilder::new()
                .authenticate(SecretKeyCredential::new("".to_string(), "".to_string()))
                .build()
                .unwrap(),
            "docs",
        )
        .unwrap();

        assert_eq!(client.url.to_string(), "https://www.smarty.com/docs");
    }
}