package eu.toldi.rss;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;


@XStreamAlias("feed")
public class Feed {
    private URL link;
    private String name;
    @XStreamAlias("articleList")
    private List<Article> articleList = null;

    public String getName() {
        return name;
    }

    public Feed(URL url) {
        articleList = new ArrayList<>();
        try {
            link = url;
            updateFeed();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Feed(String name) {
        this.name = name;
    }

    public int getArticleCount() {
        return articleList.size();
    }

    public Article get(int i) {
        return articleList.get(i);
    }

    public void updateFeed() throws IOException {
        URLConnection con = link.openConnection();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newDefaultInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(con.getInputStream());
            name = doc.getElementsByTagName("title").item(0).getTextContent();

            NodeList items = doc.getElementsByTagName("item");
            for (int i = 0; i < items.getLength(); i++) {
                Node article = items.item(i);
                Article a = new Article(article,DateTimeFormatter.RFC_1123_DATE_TIME);
                articleList.add(a);
            }
        } catch (ParserConfigurationException | SAXException e) {
            e.printStackTrace();
        }

    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean hasAricle(Article a){
        for (Article art:articleList) {
            if(a.getURL().equals(a.getURL()))
                return true;
        }
        return false;
    }

    public void addArticle(Article a)
    {
        if(!hasAricle(a))
        articleList.add(a);
    }

    public DefaultMutableTreeNode getTreeNode(){
        return new DefaultMutableTreeNode(this);
    }

    public String getLink() {
        return link.toString();
    }

    public List<Article> getArticleList() {
        return articleList;
    }

    @Override
    public String toString() {
        return name;
    }
}
