use super::Feedbin;
use super::config::AccountConfig;
use crate::feed_api::{ApiMetadata, FeedApi, FeedApiError, FeedApiResult, Portal};
use crate::models::{
    ApiSecret, DirectLoginGUI, LoginGUI, PluginID, PluginIcon, PluginInfo, ServiceLicense, ServicePrice, ServiceType, Url, VectorIcon,
};
use feedbin_api::FeedbinApi;
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/feedbin/icons"]
struct FeedbinResources;

pub struct FeedbinMetadata;

impl FeedbinMetadata {
    pub fn get_id() -> PluginID {
        PluginID::new("feedbin")
    }
}

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

    fn info(&self) -> FeedApiResult<PluginInfo> {
        let icon_data = FeedbinResources::get("feed-service-feedbin.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 = FeedbinResources::get("feed-service-feedbin-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::default());

        Ok(PluginInfo {
            id: self.id(),
            name: String::from("feedbin"),
            icon: Some(icon),
            icon_symbolic: Some(symbolic_icon),
            // It's impossible for this to fail to parse so the unwrap is safe
            website: Some(Url::parse("https://feedbin.com/").unwrap()),
            service_type: ServiceType::Remote { self_hosted: false },
            license_type: ServiceLicense::MIT,
            service_price: ServicePrice::Paid,
            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<FeedbinApi> = 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()
        {
            api = Some(FeedbinApi::new(&url, username, password));
        }

        let feedbin = Feedbin {
            api,
            portal,
            config: Arc::new(RwLock::new(account_config)),
        };
        let feedbin = Box::new(feedbin);
        Ok(feedbin)
    }
}
