use super::config::AccountConfig;
use super::{Miniflux, MinifluxApi};
use crate::feed_api::{ApiMetadata, FeedApi, FeedApiError, FeedApiResult, Portal};
use crate::models::{
    ApiSecret, DirectLoginGUI, LoginGUI, PluginID, PluginIcon, PluginInfo, ServiceLicense, ServicePrice, ServiceType, Url, VectorIcon,
};
use rust_embed::RustEmbed;
use std::path::Path;
use std::str;
use std::sync::Arc;

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

pub struct MinifluxMetadata;

impl MinifluxMetadata {
    pub fn get_id() -> PluginID {
        PluginID::new("miniflux")
    }
}

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

    fn info(&self) -> FeedApiResult<PluginInfo> {
        let icon_data = MinifluxResources::get("feed-service-miniflux.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 = MinifluxResources::get("feed-service-miniflux-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 {
            support_token_login: true,
            ..Default::default()
        });

        Ok(PluginInfo {
            id: self.id(),
            name: String::from("Miniflux"),
            icon: Some(icon),
            icon_symbolic: Some(symbolic_icon),
            website: Url::parse("https://miniflux.app/").ok(),
            service_type: ServiceType::Remote { self_hosted: true },
            license_type: ServiceLicense::ApacheV2,
            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<MinifluxApi> = None;

        if let Some(url) = account_config.get_url()
            && let Ok(url) = Url::parse(&url)
        {
            if let (Some(username), Some(password)) = (account_config.get_user_name(), account_config.get_password()) {
                api = Some(MinifluxApi::new(&url, username, password));
            } else if let Some(token) = account_config.get_token() {
                api = Some(MinifluxApi::new_from_token(&url, token));
            }
        }

        let logged_in = api.is_some();

        let miniflux = Miniflux {
            api,
            portal: Arc::new(portal),
            logged_in,
            config: account_config,
        };
        let miniflux = Box::new(miniflux);
        Ok(miniflux)
    }
}
