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
use handlebars::{
    Context, Handlebars, Helper, HelperDef, HelperResult, Output, RenderContext, RenderErrorReason,
    Renderable,
};

use fluent_bundle::FluentValue;
use handlebars::template::{Parameter, TemplateElement};
use serde_json::Value as Json;
use std::collections::HashMap;
use std::io;

use crate::Loader;

pub struct FluentHelper<L> {
    loader: L,
}

impl<L> FluentHelper<L> {
    pub fn new(loader: L) -> Self {
        Self { loader }
    }
}

#[derive(Default)]
struct StringOutput {
    pub s: String,
}

impl Output for StringOutput {
    fn write(&mut self, seg: &str) -> Result<(), io::Error> {
        self.s.push_str(seg);
        Ok(())
    }
}

impl<L: Loader + Send + Sync> HelperDef for FluentHelper<L> {
    fn call<'reg: 'rc, 'rc>(
        &self,
        h: &Helper<'rc>,
        reg: &'reg Handlebars,
        context: &'rc Context,
        rcx: &mut RenderContext<'reg, 'rc>,
        out: &mut dyn Output,
    ) -> HelperResult {
        let id = if let Some(id) = h.param(0) {
            id
        } else {
            return Err(RenderErrorReason::ParamNotFoundForIndex("fluent", 0).into());
        };

        if id.relative_path().is_some() {
            return Err(RenderErrorReason::ParamTypeMismatchForName(
                "fluent",
                "0".into(),
                "string with no path".into(),
            )
            .into());
        }

        let id = if let Json::String(ref s) = *id.value() {
            s
        } else {
            return Err(RenderErrorReason::ParamTypeMismatchForName(
                "fluent",
                "0".into(),
                "string".into(),
            )
            .into());
        };

        let mut args = if h.hash().is_empty() {
            None
        } else {
            let map = h
                .hash()
                .iter()
                .filter_map(|(k, v)| {
                    let json = v.value();
                    let val = match json {
                        // `Number::as_f64` can't fail here because we haven't
                        // enabled `arbitrary_precision` feature
                        // in `serde_json`.
                        Json::Number(n) => n.as_f64().unwrap().into(),
                        Json::String(s) => s.to_owned().into(),
                        _ => return None,
                    };
                    Some((&**k, val))
                })
                .collect();
            Some(map)
        };

        if let Some(tpl) = h.template() {
            if args.is_none() {
                args = Some(HashMap::new());
            }
            let args = args.as_mut().unwrap();
            for element in &tpl.elements {
                if let TemplateElement::HelperBlock(ref block) = element {
                    if block.name != Parameter::Name("fluentparam".into()) {
                        return Err(RenderErrorReason::Other(format!(
                            "{{{{fluent}}}} can only contain {{{{fluentparam}}}} elements, not {}",
                            block.name.expand_as_name(reg, context, rcx).unwrap()
                        ))
                        .into());
                    }
                    let id = if let Some(el) = block.params.first() {
                        if let Parameter::Literal(Json::String(ref s)) = *el {
                            s
                        } else {
                            return Err(RenderErrorReason::ParamTypeMismatchForName(
                                "fluentparam",
                                "0".into(),
                                "string".into(),
                            )
                            .into());
                        }
                    } else {
                        return Err(
                            RenderErrorReason::ParamNotFoundForIndex("fluentparam", 0).into()
                        );
                    };
                    if let Some(ref tpl) = block.template {
                        let mut s = StringOutput::default();
                        tpl.render(reg, context, rcx, &mut s)?;
                        args.insert(id, FluentValue::String(s.s.into()));
                    }
                }
            }
        }
        let lang = context
            .data()
            .get("lang")
            .expect("Language not set in context")
            .as_str()
            .expect("Language must be string")
            .parse()
            .expect("Language not valid identifier");

        let response = self.loader.lookup(&lang, id, args.as_ref());
        out.write(&response)
            .map_err(|e| RenderErrorReason::NestedError(Box::new(e)).into())
    }
}