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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/*
 * Copyright (C) 2021  Aravinth Manivannan <realaravinth@batsense.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
use std::{collections::HashMap, hash::Hash};

use crate::data::*;
use crate::proxy::StringUtils;
use get_post::*;

#[derive(Eq, PartialEq)]
enum PostitionType {
    Start,
    End,
}

struct ListState {
    in_uli: bool,
    in_oli: bool,
}

impl Default for ListState {
    fn default() -> Self {
        Self {
            in_uli: false,
            in_oli: false,
        }
    }
}

struct Markup<'a, 'b> {
    markup: &'a GetPostPostContentBodyModelParagraphsMarkups,
    p: &'a GetPostPostContentBodyModelParagraphs,
    pos_type: PostitionType,
    gists: &'b Option<Vec<(String, crate::data::GistContent)>>,
}

impl<'a, 'b> Markup<'a, 'b> {
    fn start(
        p: &GetPostPostContentBodyModelParagraphs,
        gists: &'b Option<Vec<(String, crate::data::GistContent)>>,
        pindex: usize,
        state: &mut ListState,
    ) -> String {
        let list = Self::list_close(p, state);
        let resp = if p.type_ == "IMG" {
            let metadata = p.metadata.as_ref().unwrap();
            format!(
                r#"<figure><img width="{}" src="{}" /> <figcaption>"#,
                metadata.original_width.as_ref().unwrap(),
                crate::V1_API_ROUTES.proxy.get_medium_asset(&metadata.id)
            )
        } else if p.type_ == "P" {
            "<p>".into()
        } else if p.type_ == "PRE" {
            "<pre>".into()
        } else if p.type_ == "BQ" || p.type_ == "PQ" {
            "<blockquote>".into()
        } else if p.type_ == "H1" {
            "<h1>".into()
        } else if p.type_ == "H2" {
            "<h2>".into()
        } else if p.type_ == "H3" {
            if pindex == 0 {
                log::debug!("caught heading");
                "".into()
            } else {
                "<h3>".into()
            }
        } else if p.type_ == "H4" {
            "<h4>".into()
        } else if p.type_ == "H5" {
            "<h5>".into()
        } else if p.type_ == "H6" {
            "<h6>".into()
        } else if p.type_ == "IFRAME" {
            let src = &p
                .iframe
                .as_ref()
                .unwrap()
                .media_resource
                .as_ref()
                .unwrap()
                .href;
            if src.contains("gist.github.com") {
                let gist_id = crate::data::Data::get_gist_id(src);
                let (_, gist) = gists
                    .as_ref()
                    .unwrap()
                    .iter()
                    .find(|(id, _)| id == gist_id)
                    .as_ref()
                    .unwrap();

                let mut gists = String::default();
                for file in &gist.files {
                    gists += &format!(
                        r#"<div class="code-block gist-block">{}</div>"#,
                        file.get_html_content()
                    );
                }
                format!(
                    r#"<div class="gist_container">{gists}
                     <a class="gist_link" href="{}" target="_blank">See gist on GitHub</a>"#,
                    &gist.html_url
                )
            } else {
                format!(r#"<iframe src="{src}" frameborder="0">"#)
            }
        } else if p.type_ == "ULI" {
            if state.in_uli {
                "<li>".into()
            } else {
                state.in_uli = true;
                "<ul><li>".into()
            }
        } else if p.type_ == "OLI" {
            if state.in_oli {
                "<li>".into()
            } else {
                state.in_oli = true;
                "<ol><li>".into()
            }
        } else if p.type_ == "MIXTAPE_EMBED" {
            "<div class='mixtape'><p>".into()
        } else {
            log::info!("Unknown type: {}", p.type_);
            r#"
                <p class="libmedium__meta">
                    <b>From LibMedium:</b> LibMedium is built by reverse
                    engineering the Meduim's internal API. This post contains
                    markup(formatting rules) that we are unaware of.
                    Please report this URL <a
                    href="https://github.com/realaravinth/libmedium/issues/1"
                    rel="noreferrer">on our bug tracker</a> so that we can
                    improve page rendering.
                    <br />
                    Alternatively, you can also email me at realaravinth at batsense dot net!
                  </p>
            <span>"#
                .into()
        };

        match list {
            Some(list) => format!("{list}{resp}"),
            None => resp,
        }
    }

    fn end(
        p: &GetPostPostContentBodyModelParagraphs,
        pindex: usize,
        state: &mut ListState,
    ) -> String {
        let resp: String = if p.type_ == "IMG" {
            "</figcaption></figure>".into()
        } else if p.type_ == "P" {
            "</p>".into()
        } else if p.type_ == "PRE" {
            "</pre>".into()
        } else if p.type_ == "BQ" || p.type_ == "PQ" {
            "</blockquote>".into()
        } else if p.type_ == "H1" {
            "</h1>".into()
        } else if p.type_ == "H2" {
            "</h2>".into()
        } else if p.type_ == "H3" {
            if pindex == 0 {
                log::debug!("caught heading");
                "".into()
            } else {
                "</h3>".into()
            }
        } else if p.type_ == "H4" {
            "</h4>".into()
        } else if p.type_ == "H5" {
            "</h5>".into()
        } else if p.type_ == "H6" {
            "</h6>".into()
        } else if p.type_ == "IFRAME" {
            let src = &p
                .iframe
                .as_ref()
                .unwrap()
                .media_resource
                .as_ref()
                .unwrap()
                .href;
            if src.contains("gist.github.com") {
                "</div>".into()
            } else {
                "</iframe>".into()
            }
        } else if p.type_ == "OLI" || p.type_ == "ULI" {
            "</li>".into()
        } else if p.type_ == "MIXTAPE_EMBED" {
            "</p></div>".into()
        } else {
            "</span>".into()
        };
        if state.in_oli {
            if p.type_ != "OLI" {
                state.in_oli = false;
                format!("</ol>{resp}")
            } else {
                resp
            }
        } else if state.in_uli {
            if p.type_ != "ULI" {
                state.in_uli = false;
                format!("</ul>{resp}")
            } else {
                resp
            }
        } else {
            resp
        }
    }

    fn list_close(
        p: &GetPostPostContentBodyModelParagraphs,
        state: &mut ListState,
    ) -> Option<String> {
        if state.in_oli {
            if p.type_ != "OLI" {
                state.in_oli = false;
                return Some(format!("</ol>"));
            }
        };
        if state.in_uli {
            if p.type_ != "ULI" {
                state.in_uli = false;
                return Some(format!("</ul>"));
            }
        };
        None
    }

    fn apply_markup(&self, pindex: usize) -> String {
        if self.markup.type_ == "A" {
            if let Some(anchor_type) = &self.markup.anchor_type {
                if anchor_type == "LINK" {
                    if self.pos_type == PostitionType::Start {
                        format!(
                            r#"<a rel="noreferrer" href="{}">"#,
                            self.markup.href.as_ref().unwrap()
                        )
                    } else {
                        "</a>".into()
                    }
                } else if anchor_type == "USER" {
                    if self.pos_type == PostitionType::Start {
                        format!(
                            r#"<a rel="noreferrer" href="https://medium.com/u/{}">"#,
                            self.markup.user_id.as_ref().unwrap()
                        )
                    } else {
                        "</a>".into()
                    }
                } else {
                    //             log::error!("unknown markup.anchor_type: {:?} post id {}", anchor_type, id);
                    if self.pos_type == PostitionType::Start {
                        "<span>".into()
                    } else {
                        "</span>".into()
                    }
                }
            } else {
                //             log::error!("unknown markup.anchor_type: {:?} post id {}", anchor_type, id);
                if self.pos_type == PostitionType::Start {
                    "<span>".into()
                } else {
                    "</span>".into()
                }
            }
        } else if self.markup.type_ == "PRE" {
            if self.pos_type == PostitionType::Start {
                "<pre>".into()
            } else {
                "</pre>".into()
            }
        } else if self.markup.type_ == "EM" {
            if self.pos_type == PostitionType::Start {
                "<em>".into()
            } else {
                "</em>".into()
            }
        } else if self.markup.type_ == "STRONG" {
            if self.pos_type == PostitionType::Start {
                "<strong>".into()
            } else {
                "</strong>".into()
            }
        } else if self.markup.type_ == "CODE" {
            if self.pos_type == PostitionType::Start {
                "<code>".into()
            } else {
                "</code>".into()
            }
        } else {
            // log::error!("unknown markup.type_: {:?} post id {}", markup.type_, id);
            if self.pos_type == PostitionType::Start {
                log::info!("Unknown type");
                r#"
                <p class="libmedium__meta">
                    <b>From LibMedium:</b> LibMedium is built by reverse
                    engineering the Meduim's internal API. This post contains
                    markup(formatting rules) that we are unaware of.
                    Please report this URL <a
                    href="https://github.com/realaravinth/libmedium/issues/1"
                    rel="noreferrer">on our bug tracker</a> so that we can
                    improve page rendering.
                    <br />
                    Alternatively, you can also email me at realaravinth at batsense dot net!
                  </p>
            <span>"#
                    .into()
            } else {
                "</span>".into()
            }
        }
    }
}

#[derive(Default)]
struct PositionMap<'a, 'b> {
    map: HashMap<i64, Vec<Markup<'a, 'b>>>,
    arr: Vec<i64>,
}

impl<'a, 'b> PositionMap<'a, 'b> {
    fn insert_if_not_exists(&mut self, pos: i64, m: Markup<'a, 'b>) {
        if let Some(markups) = self.map.get_mut(&pos) {
            markups.push(m);
        } else {
            self.map.insert(pos, vec![m]);
            self.arr.push(pos);
        }
    }
}

pub fn apply_markup<'b>(
    data: &PostResp,
    gists: &'b Option<Vec<(String, crate::data::GistContent)>>,
) -> Vec<String> {
    let mut paragraphs: Vec<String> = Vec::with_capacity(data.content.body_model.paragraphs.len());
    let mut state = ListState::default();
    for (pindex, p) in data.content.body_model.paragraphs.iter().enumerate() {
        let mut pos = PositionMap::default();
        if p.type_ == "H3" && pindex == 0 {
            log::debug!("FOUND TOP LEVEL H3. Breaking");
            continue;
        }
        for m in p.markups.iter() {
            let start_markup = Markup {
                markup: &m,
                p,
                gists,
                pos_type: PostitionType::Start,
            };
            pos.insert_if_not_exists(m.start, start_markup);
            let end_markup = Markup {
                markup: &m,
                p,
                gists,
                pos_type: PostitionType::End,
            };

            pos.insert_if_not_exists(m.end, end_markup);
        }

        let mut cur = 0;

        fn incr_cur(cur: usize, point: i64) -> usize {
            let incr = point as usize - cur;
            let post_incr = cur + incr;
            log::debug!(
                "cur before incr: {cur}, incr by: {}, post incr: {}",
                incr,
                post_incr
            );
            post_incr
        }

        let mut content = String::with_capacity(p.text.len());
        content += &Markup::start(&p, &gists, pindex, &mut state);
        pos.arr.sort();
        if let Some(first) = pos.arr.get(0) {
            //content += p.text.substring(cur, *first as usize);
            content += p.text.slice(cur..*first as usize);
            cur = incr_cur(cur, *first);
            for point in pos.arr.iter() {
                //content.push(p.text.substring(start, start + point);
                //            if *point != 0 {

                if cur != *point as usize {
                    //           content += p.text.substring(cur, *point as usize);
                    content += p.text.slice(cur..*point as usize);
                }
                //           }
                let pos_markups = pos.map.get(point).unwrap();
                for m in pos_markups.iter() {
                    content += &m.apply_markup(pindex);
                }
                cur = incr_cur(cur, *point);
            }
            log::debug!("LAST");
            content += p.text.slice(cur..);
            content += &Markup::end(&p, pindex, &mut state);
        } else {
            log::debug!("LAST WITH NO MARKUP");
            content += p.text.slice(cur..);
            content += &Markup::end(&p, pindex, &mut state);
        }
        paragraphs.push(content);
    }
    paragraphs
}