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
// Copyright 2023 Fondazione LINKS

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.



use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;


use crate::flattening::json_value_flattening;

use super::payloads::Payloads;

#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct Claims (pub Vec<String>);

/** These claims are taken from the JWT RFC (https://tools.ietf.org/html/rfc7519) 
 * making the hypothesis that in the future will be used also for the JPTs **/

#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct JptClaims {

    /// Apparently the "iss" that in JWT was a claim, now should be an issuer protected header parameter 
    /** Apparently the "aud" that in JWT was a claim, now should be an presentation protected header parameter 
      * (https://datatracker.ietf.org/doc/html/draft-ietf-jose-json-web-proof#name-presentation-protected-head) **/
    
    /// Subject of the JPT.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sub: Option<String>,
    /// Expiration time
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exp: Option<i64>,
    /// Time before which the JPT MUST NOT be accepted
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nbf: Option<i64>,
    /// Issue time
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iat: Option<i64>,
    /// Unique ID for the JPT.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jti: Option<String>,
    // Other claims (age, name, surname, ...)
    // #[serde(flatten, skip_serializing_if = "Option::is_none")]
    // pub custom: Option<Value>
    #[serde(flatten)]
    pub custom: IndexMap<String, Value>
}


impl JptClaims {

    pub fn new() -> Self {
        Self { 
            sub: None,
            exp: None, 
            nbf: None, 
            iat: None, 
            jti: None, 
            custom: IndexMap::new() }
    }

    pub fn set_sub(&mut self, value: String) {
        self.sub = Some(value);
    }

    pub fn set_exp(&mut self, value: i64) {
        self.exp = Some(value);
    }

    pub fn set_nbf(&mut self, value: i64) {
        self.nbf = Some(value);
    }

    pub fn set_iat(&mut self, value: i64) {
        self.iat = Some(value);
    }

    pub fn set_jti(&mut self, value: String) {
        self.jti = Some(value);
    }

    pub fn add_claim<T: Serialize>(&mut self, claim: &str, value: T, flattened: bool) {
        let serde_value = serde_json::to_value(value).unwrap();
        if flattened {
            self.custom.extend(json_value_flattening(serde_value));
            // json_value_flattening(serde_value).iter().for_each(|(k, v)| self.custom.insert(k, v))
        } else {
            self.custom.insert(claim.to_owned(), serde_value);
        }
        
    }

    /// Extracts claims and payloads into separate vectors.
    pub fn get_claims_and_payloads(&self) -> (Claims, Payloads){

        let jptclaims_json_value = serde_json::to_value(self).unwrap();
        let claim_payloads_pairs = json_value_flattening(jptclaims_json_value);     
        // let flattened = Flattener::new()
        // .set_key_separator(".")
        // .set_array_formatting(ArrayFormatting::Surrounded {
        //     start: "[".to_string(),
        //     end: "]".to_string()
        // })
        // .set_preserve_empty_arrays(false)
        // .set_preserve_empty_objects(false)
        // .flatten(&jptclaims_json_value).unwrap();

        // println!("flattened: {}", flattened);

        
        // let claim_payload_pairs: IndexMap<String, Value> = serde_json::from_value::<IndexMap<String, Value>>(flattened.clone()).unwrap();

        let (keys, values): (Vec<String>, Vec<Value>) = claim_payloads_pairs.into_iter().unzip();

        (Claims(keys), Payloads::new_from_values(values))
        
    }


    // pub fn from_attributes(attributes: BTreeMap<String, String>) -> Result<JptClaims, serde_json::Error> {
    //     let mut claims = JptClaims::default();

    //     for (key, value) in attributes {
    //         match key.as_str() {
    //             "sub" => claims.sub = Some(value),
    //             "exp" => claims.exp = Some(value.parse::<i64>().unwrap_or(0)), // Handle parsing errors
    //             "nbf" => claims.nbf = Some(value.parse::<i64>().unwrap_or(0)), // Handle parsing errors
    //             "iat" => claims.iat = Some(value.parse::<i64>().unwrap_or(0)), // Handle parsing errors
    //             "jti" => claims.jti = Some(value),
    //             _ => {
    //                 // Parse custom claims as JSON strings
    //                 if claims.custom.is_none() {
    //                     claims.custom = Some(Value::Object(Default::default()));
    //                 }

    //                 if let Some(custom) = claims.custom.as_mut() {
    //                     if let Value::Object(custom_object) = custom {
    //                         custom_object.insert(key, serde_json::from_str(&value)?);
    //                     }
    //                 }
    //             }
    //         }
    //     }

    //     Ok(claims)
    // }
  
}