use std::{fs::{self, OpenOptions}, path::Path, io::Write};

use lemmy_api_common::sensitive::Sensitive;
use serde_derive::{Deserialize, Serialize};

macro_rules! pub_struct {
    ($name:ident {$($field:ident: $t:ty,)*}) => {
        #[derive(Serialize, Deserialize, Clone)]
        pub(crate) struct $name {
            $(pub(crate) $field: $t), *
        }
    }
}

// Secrets structs
pub_struct!(Secrets {
    lemmy: LemmyLogin,
    reddit: RedditLogin,
});

impl Secrets {
    pub(crate) fn load() -> Secrets {
        let file_contents = match fs::read_to_string("secrets.json") {
            Ok(data) => data,
            Err(e) => panic!("ERROR: secrets.json could not be read:\n\n{:#?}", e),
        };
        let config_parse: Secrets = match serde_json::from_str(&file_contents) {
            Ok(data) => data,
            Err(e) => panic!("ERROR: secrets.json could not be parsed:\n\n{:#?}", e),
        };

        return config_parse;
    }
}

#[derive(Serialize, Deserialize, Clone)]
pub(crate) struct LemmyLogin {
    pub(crate) username: String,
    password: String
}

impl LemmyLogin {
    pub(crate) fn get_username(&self) -> Sensitive<String> {
        return Sensitive::new(self.username.clone());
    }

    pub(crate) fn get_password(&self) -> Sensitive<String> {
        return Sensitive::new(self.password.clone())
    }
}

#[derive(Serialize, Deserialize, Clone)]
pub(crate) struct RedditLogin {
    pub(crate) app_id: String,
    app_secret: String,
    refresh_token: String,
    redirect_uri: String,
}

// Config structs
pub_struct!(Config {
    reddit_config: RedditConfig,
    feeds: Vec<FeedSetting>,
});

impl Config {
    pub(crate) fn load() -> Config {
        let file_contents = match fs::read_to_string("config.json") {
            Ok(data) => data,
            Err(e) => panic!("ERROR: config.json could not be read:\n\n{:#?}", e),
        };
        let config_parse: Config = match serde_json::from_str(&file_contents) {
            Ok(data) => data,
            Err(e) => panic!("ERROR: config.json could not be parsed:\n\n{:#?}", e),
        };

        return config_parse;
    }
}

pub_struct!(RedditConfig {
    user_agent: String,
    subreddit: String,
});

pub_struct!(FeedSetting {
    feed_url: String,
    communities: FeedCommunities,
    reddit: FeedRedditSettings,
});

pub_struct!(FeedCommunities {
    chapter: LemmyCommunities,
    volume: LemmyCommunities,
});

#[derive(Serialize, Deserialize, Clone)]
#[allow(non_camel_case_types)]
pub(crate) enum LemmyCommunities {
    aobwebnovel,
    aobprepub,
    aoblightnovel,
    aobmanga,
    aobanime
}

pub_struct!(FeedRedditSettings {
    enabled: bool,
    flair: String,
});

// Posts structs
pub_struct!(PrevPost {
    title: String,
    last_post_url: String,
});

impl PrevPost {
    pub(crate) fn load() -> Vec<PrevPost> {
        let history;
        
        if Path::new("posts.json").exists() {
            let file_contents = match fs::read_to_string("posts.json") {
                Ok(data) => data,
                Err(e) => panic!("ERROR: secrets.json could not be read:\n\n{:#?}", e),
            };

            if file_contents.len() > 0 {
                let history_parse: Vec<PrevPost> = match serde_json::from_str(&file_contents) {
                    Ok(data) => data,
                    Err(e) => panic!("ERROR: secrets.json could not be parsed:\n\n{:#?}", e),
                };
                history = history_parse;
            }
            else {
                history = [].to_vec()
            }
        }
        else {
            let _ = fs::File::create("posts.json");
            history = [].to_vec()
        }

        return history;
    }

    pub(crate) fn save(data: &Vec<PrevPost>) {
        let mut file = OpenOptions::new().read(true).write(true).create(true).open("posts.json").unwrap();

        let json_data = serde_json::to_string_pretty(&data).unwrap();

        write!(&mut file, "{}", json_data).unwrap();
    }
}

// RSS Feed Structs
pub_struct!(FeedData {
    version: String,
    title: String,
    home_page_url: String,
    description: String,
    author: FeedAuthor,
    items: Vec<FeedEntry>,
});

pub_struct!(FeedAuthor {
    name: String,
});

pub_struct!(FeedEntry {
    id: String,
    url: String,
    title: String,
    summary: String,
    image: Option<String>,
    date_published: String,
});