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
use std::error::Error;

use inquire::formatter::OptionFormatter;
use inquire::Select;
use reqwest::header::AUTHORIZATION;
use serde_json::Value;

use crate::{
    auth::{get_access_token, reauthenticate},
    mal::{Anime, AnimeList},
};

pub struct ListArgs {
    num: Option<i32>,
}

impl ListArgs {
    pub fn new(num: Option<i32>) -> Self {
        Self { num }
    }
}

pub async fn show_list(args: ListArgs) -> Result<(), Box<dyn Error + Send>> {
    let access_token = get_access_token().await.unwrap();
    let client = reqwest::Client::new();

    let num_anime = match args.num {
        Some(num) => num,
        _ => 10,
    };
    // post request
    let response = client
        .get(format!("https://api.myanimelist.net/v2/users/@me/animelist?fields=list_status&limit={num_anime}"))
        .header(AUTHORIZATION, format!("Bearer {}", &access_token))
        .send()
        .await
        .unwrap();

    if response.status().is_success() {
        let response_text = response.text().await.unwrap();
        let response_json: Value = serde_json::from_str(response_text.as_str()).unwrap();

        let formatter: OptionFormatter<AnimeList> =
            &|i| format!("\nSelected - {}", (*i.value).clone().get_title());
        loop {
            let anime_list = parse_anime_list_from_json(&response_json);
            let anime = Select::new("Status\tCompleted\tTitle", anime_list)
                .with_page_size(10)
                .with_formatter(formatter)
                .prompt();

            match anime {
                Ok(anime) => show_anime_details(anime.get_id()).await,
                Err(_) => {
                    break;
                }
            }
        }
    } else {
        // reuauthenticate and try again
        let _ = reauthenticate().await;
        println!("Reauthenticated token. Please try again...")
    }
    Ok(())
}

pub fn parse_anime_list_from_json(json: &Value) -> Vec<AnimeList> {
    let data: &Value = json.get("data").unwrap();

    data.as_array()
        .unwrap()
        .iter()
        .map(|anime| AnimeList::new(anime))
        .collect::<Vec<AnimeList>>()
}

pub async fn show_anime_details(id: i64) {
    /*
       Get details about the anime
    */
    let access_token = get_access_token().await.unwrap();
    let client = reqwest::Client::new();
    let response = client
            .get(
                format!(
                    "https://api.myanimelist.net/v2/anime/{}?fields=id,title,start_date,end_date,synopsis,mean,rank",
                    id
                )
            )
            .header(AUTHORIZATION, format!("Bearer {}", &access_token))
            .send()
            .await
            .unwrap();

    if response.status().is_success() {
        let response_text = response.text().await.unwrap();
        let anime: Anime = serde_json::from_str(&response_text).unwrap();
        println!("{}", anime);
    }

    let options: Result<String, inquire::InquireError> = Select::new(
        "Options",
        vec!["Go back".to_string(), "Open MAL page".to_string()],
    )
    .prompt();

    match options {
        Ok(choice) => {
            if choice == "Open MAL page" {
                open_url(id);
            }
        }
        _ => (),
    }
}

pub fn open_url(id: i64) {
    open::that(format!("https://myanimelist.net/anime/{}", id)).unwrap();
}