use super::config::AccountConfig;
use super::{FreshRss, GReaderApi};
use crate::feed_api::{ApiMetadata, FeedApi, FeedApiError, FeedApiResult, Portal};
use crate::models::{
    ApiSecret, DirectLoginGUI, LoginGUI, PluginID, PluginIcon, PluginInfo, ServiceLicense, ServicePrice, ServiceType, Url, VectorIcon,
};
use greader_api::models::PostToken;
use greader_api::{AuthData, GoogleAuth};
use rust_embed::RustEmbed;
use std::path::Path;
use std::str;
use std::sync::Arc;
use tokio::sync::RwLock;

#[derive(RustEmbed)]
#[folder = "src/feed_api_implementations/freshrss/icons"]
struct FreshRssResources;

pub struct FreshRssMetadata;

impl FreshRssMetadata {
    pub fn get_id() -> PluginID {
        PluginID::new("freshrss")
    }
}

impl ApiMetadata for FreshRssMetadata {
    fn id(&self) -> PluginID {
        Self::get_id()
    }

    fn info(&self) -> FeedApiResult<PluginInfo> {
        let icon_data = FreshRssResources::get("feed-service-freshrss.svg").ok_or(FeedApiError::Resource)?;
        let icon = VectorIcon {
            data: icon_data.data.to_vec(),
            width: 48,
            height: 48,
        };
        let icon = PluginIcon::Vector(icon);

        let symbolic_icon_data = FreshRssResources::get("feed-service-freshrss-symbolic.svg").ok_or(FeedApiError::Resource)?;
        let symbolic_icon = VectorIcon {
            data: symbolic_icon_data.data.to_vec(),
            width: 48,
            height: 48,
        };
        let symbolic_icon = PluginIcon::Vector(symbolic_icon);

        let login_gui = LoginGUI::Direct(DirectLoginGUI {
            http_auth: true,
            ..Default::default()
        });

        Ok(PluginInfo {
            id: self.id(),
            name: String::from("FreshRSS"),
            icon: Some(icon),
            icon_symbolic: Some(symbolic_icon),
            website: Url::parse("https://freshrss.org").ok(),
            service_type: ServiceType::Remote { self_hosted: true },
            license_type: ServiceLicense::AGPLv3,
            service_price: ServicePrice::Free,
            login_gui,
        })
    }

    fn get_instance(&self, config_dir: &Path, portal: Box<dyn Portal>, _user_api_secret: Option<ApiSecret>) -> FeedApiResult<Box<dyn FeedApi>> {
        let account_config = AccountConfig::load(config_dir)?;
        let mut api: Option<GReaderApi> = None;

        if let Some(url) = account_config.get_url()
            && let Ok(url) = Url::parse(&url)
            && let Some(username) = account_config.get_user_name()
            && let Some(password) = account_config.get_password()
        {
            let url_with_slash = Url::parse(&(url.as_str().to_owned() + "/")).unwrap();
            api = Some(GReaderApi::new(
                &url_with_slash,
                AuthData::Google(GoogleAuth {
                    username,
                    password,
                    auth_token: account_config.get_auth_token(),
                    post_token: account_config.get_post_token().map(|t| PostToken::new(&t)),
                }),
            ));
        }

        let logged_in = api.is_some();

        let freshrss = FreshRss {
            api,
            portal: Arc::new(portal),
            logged_in,
            config: RwLock::new(account_config),
        };
        let template = Box::new(freshrss);
        Ok(template)
    }
}
