use crate::feed_api::{FeedApi, FeedApiError};
use crate::models::{ArticleID, CategoryID, Config, FatArticle, FeedID, FeedMapping, Marked, Read, SyncResult, TagID, Tagging};
use parking_lot::RwLock;
use reqwest::Client;
use std::collections::HashSet;

pub struct ActionCache {
    articles_marked_read: HashSet<ArticleID>,
    articles_marked_unread: HashSet<ArticleID>,
    articles_marked: HashSet<ArticleID>,
    articles_unmarked: HashSet<ArticleID>,
    articles_tag_added: HashSet<Tagging>,
    articles_tag_removed: HashSet<Tagging>,
    feeds_marked_read: HashSet<FeedID>,
    categories_marked_read: HashSet<CategoryID>,
    tags_marked_read: HashSet<TagID>,
}

impl ActionCache {
    pub fn new() -> Self {
        ActionCache {
            articles_marked_read: HashSet::new(),
            articles_marked_unread: HashSet::new(),
            articles_marked: HashSet::new(),
            articles_unmarked: HashSet::new(),
            articles_tag_added: HashSet::new(),
            articles_tag_removed: HashSet::new(),
            feeds_marked_read: HashSet::new(),
            categories_marked_read: HashSet::new(),
            tags_marked_read: HashSet::new(),
        }
    }

    pub fn add_article_marked_read(&mut self, id: &ArticleID) {
        if self.articles_marked_unread.contains(id) {
            self.articles_marked_unread.remove(id);
        } else {
            self.articles_marked_read.insert(id.clone());
        }
    }

    pub fn add_article_marked_unread(&mut self, id: &ArticleID) {
        if self.articles_marked_read.contains(id) {
            self.articles_marked_read.remove(id);
        } else {
            self.articles_marked_unread.insert(id.clone());
        }
    }

    pub fn add_article_mark(&mut self, id: &ArticleID) {
        if self.articles_unmarked.contains(id) {
            self.articles_unmarked.remove(id);
        } else {
            self.articles_marked.insert(id.clone());
        }
    }

    pub fn add_article_unmark(&mut self, id: &ArticleID) {
        if self.articles_marked.contains(id) {
            self.articles_marked.remove(id);
        } else {
            self.articles_unmarked.insert(id.clone());
        }
    }

    pub fn add_article_tagged(&mut self, article_id: &ArticleID, tag_id: &TagID) {
        let tag_article_model = Tagging {
            article_id: article_id.clone(),
            tag_id: tag_id.clone(),
        };
        if self.articles_tag_removed.contains(&tag_article_model) {
            self.articles_tag_removed.remove(&tag_article_model);
        } else {
            self.articles_tag_added.insert(tag_article_model);
        }
    }

    pub fn add_article_untagged(&mut self, article_id: &ArticleID, tag_id: &TagID) {
        let tag_article_model = Tagging {
            article_id: article_id.clone(),
            tag_id: tag_id.clone(),
        };
        if self.articles_tag_added.contains(&tag_article_model) {
            self.articles_tag_added.remove(&tag_article_model);
        } else {
            self.articles_tag_removed.insert(tag_article_model);
        }
    }

    pub fn add_feed_mark_read(&mut self, id: &FeedID) {
        self.feeds_marked_read.insert(id.clone());
    }

    pub fn add_category_mark_read(&mut self, id: &CategoryID) {
        self.categories_marked_read.insert(id.clone());
    }

    pub fn add_tag_mark_read(&mut self, id: &TagID) {
        self.tags_marked_read.insert(id.clone());
    }

    pub fn process_sync_result(&self, sync_result: SyncResult) -> SyncResult {
        let (feeds, categories, mappings, tags, headlines, articles, enclosures, taggings) = sync_result.decompose();

        // mark read
        let articles = if !self.articles_marked_read.is_empty() {
            articles.map(|vec| {
                vec.into_iter()
                    .map(|mut a| {
                        if self.articles_marked_read.contains(&a.article_id) {
                            a.unread = Read::Read
                        }
                        a
                    })
                    .collect::<Vec<FatArticle>>()
            })
        } else {
            articles
        };

        // mark unread
        let articles = if !self.articles_marked_unread.is_empty() {
            articles.map(|vec| {
                vec.into_iter()
                    .map(|mut a| {
                        if self.articles_marked_unread.contains(&a.article_id) {
                            a.unread = Read::Unread
                        }
                        a
                    })
                    .collect::<Vec<FatArticle>>()
            })
        } else {
            articles
        };

        // marked
        let articles = if !self.articles_marked.is_empty() {
            articles.map(|vec| {
                vec.into_iter()
                    .map(|mut a| {
                        if self.articles_marked.contains(&a.article_id) {
                            a.marked = Marked::Marked
                        }
                        a
                    })
                    .collect::<Vec<FatArticle>>()
            })
        } else {
            articles
        };

        // unmarked
        let articles = if !self.articles_unmarked.is_empty() {
            articles.map(|vec| {
                vec.into_iter()
                    .map(|mut a| {
                        if self.articles_unmarked.contains(&a.article_id) {
                            a.marked = Marked::Unmarked
                        }
                        a
                    })
                    .collect::<Vec<FatArticle>>()
            })
        } else {
            articles
        };

        // mark feeds read
        let articles = if !self.feeds_marked_read.is_empty() {
            self.process_feed_marked_read(articles, &self.feeds_marked_read)
        } else {
            articles
        };

        // mark tags read
        let articles = if !self.tags_marked_read.is_empty() {
            self.process_tag_marked_read(articles, &taggings, &self.tags_marked_read)
        } else {
            articles
        };

        // mark categories read
        let articles = if !self.categories_marked_read.is_empty() {
            let read_categories_feeds = Self::build_category_feed_ids(&self.categories_marked_read, &mappings);

            if let Some(read_categories_feeds) = read_categories_feeds {
                self.process_feed_marked_read(articles, &read_categories_feeds)
            } else {
                articles
            }
        } else {
            articles
        };

        // tag/untag articles
        let taggings = if !self.articles_tag_added.is_empty() || !self.articles_tag_removed.is_empty() {
            self.process_tag_articles(taggings, &self.articles_tag_added, &self.articles_tag_removed)
        } else {
            taggings
        };

        SyncResult {
            feeds,
            categories,
            mappings,
            tags,
            headlines,
            articles,
            enclosures,
            taggings,
        }
    }

    fn process_feed_marked_read(&self, articles: Option<Vec<FatArticle>>, feed_ids: &HashSet<FeedID>) -> Option<Vec<FatArticle>> {
        articles.map(|vec| {
            vec.into_iter()
                .map(|mut a| {
                    if feed_ids.contains(&a.feed_id) {
                        a.unread = Read::Read
                    }
                    a
                })
                .collect::<Vec<FatArticle>>()
        })
    }

    fn process_tag_marked_read(
        &self,
        articles: Option<Vec<FatArticle>>,
        taggings: &Option<Vec<Tagging>>,
        tag_ids: &HashSet<TagID>,
    ) -> Option<Vec<FatArticle>> {
        let mut tagged_articles: HashSet<ArticleID> = HashSet::new();
        if let Some(vec) = taggings {
            for tagging in vec {
                if tag_ids.contains(&tagging.tag_id) {
                    tagged_articles.insert(tagging.article_id.clone());
                }
            }
        }
        articles.map(|vec| {
            vec.into_iter()
                .map(|mut a| {
                    if tagged_articles.contains(&a.article_id) {
                        a.unread = Read::Read
                    }
                    a
                })
                .collect::<Vec<FatArticle>>()
        })
    }

    fn process_tag_articles(
        &self,
        taggings: Option<Vec<Tagging>>,
        tag_articles: &HashSet<Tagging>,
        untag_articles: &HashSet<Tagging>,
    ) -> Option<Vec<Tagging>> {
        let taggings = taggings.map(|mut vec| {
            vec.append(&mut tag_articles.iter().cloned().collect::<Vec<Tagging>>());
            vec
        });
        let taggings = taggings.map(|mut vec| {
            for t in untag_articles {
                if let Some(index) = vec.iter().position(|a| a == t) {
                    vec.remove(index);
                }
            }
            vec
        });
        taggings
    }

    fn build_category_feed_ids(category_ids: &HashSet<CategoryID>, mappings: &Option<Vec<FeedMapping>>) -> Option<HashSet<FeedID>> {
        if let Some(vec) = mappings {
            Some(
                vec.into_iter()
                    .filter_map(|m| {
                        if category_ids.contains(&m.category_id) {
                            Some(m.feed_id.clone())
                        } else {
                            None
                        }
                    })
                    .collect::<HashSet<FeedID>>(),
            )
        } else {
            None
        }
    }

    pub async fn execute_api_actions(&self, api: &RwLock<Box<dyn FeedApi>>, config: &RwLock<Config>, client: &Client) -> Result<(), FeedApiError> {
        if api.read().is_logged_in(client).await? {
            if !self.articles_marked_read.is_empty() {
                api.read()
                    .set_article_read(&self.articles_marked_read.iter().cloned().collect::<Vec<ArticleID>>(), Read::Read, client)
                    .await?;
            }
            if !self.articles_marked_unread.is_empty() {
                api.read()
                    .set_article_read(
                        &self.articles_marked_unread.iter().cloned().collect::<Vec<ArticleID>>(),
                        Read::Unread,
                        client,
                    )
                    .await?;
            }
            if !self.articles_marked.is_empty() {
                api.read()
                    .set_article_marked(&self.articles_marked.iter().cloned().collect::<Vec<ArticleID>>(), Marked::Marked, client)
                    .await?;
            }
            if !self.articles_unmarked.is_empty() {
                api.read()
                    .set_article_marked(
                        &self.articles_unmarked.iter().cloned().collect::<Vec<ArticleID>>(),
                        Marked::Unmarked,
                        client,
                    )
                    .await?;
            }
            if !self.feeds_marked_read.is_empty() {
                api.read()
                    .set_feed_read(
                        &self.feeds_marked_read.iter().cloned().collect::<Vec<FeedID>>(),
                        config.read().get_last_sync(),
                        client,
                    )
                    .await?;
            }
            if !self.categories_marked_read.is_empty() {
                api.read()
                    .set_category_read(
                        &self.categories_marked_read.iter().cloned().collect::<Vec<CategoryID>>(),
                        config.read().get_last_sync(),
                        client,
                    )
                    .await?;
            }
            if !self.tags_marked_read.is_empty() {
                api.read()
                    .set_tag_read(
                        &self.tags_marked_read.iter().cloned().collect::<Vec<TagID>>(),
                        config.read().get_last_sync(),
                        client,
                    )
                    .await?;
            }
        }
        Ok(())
    }

    pub fn reset(&mut self) {
        self.articles_marked_read = HashSet::new();
        self.articles_marked_unread = HashSet::new();
        self.articles_marked = HashSet::new();
        self.articles_unmarked = HashSet::new();
        self.articles_tag_added = HashSet::new();
        self.articles_tag_removed = HashSet::new();
        self.feeds_marked_read = HashSet::new();
        self.categories_marked_read = HashSet::new();
        self.tags_marked_read = HashSet::new();
    }
}
