package com.peetz.kontor.data;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.peetz.comics.entity.ComicEntity;
import com.peetz.comics.entity.PublisherEntity;
import com.peetz.comics.service.ComicService;

public class ImportComics
{
	public void parseNode(Node xmlNode)
	{
		NodeList childNodes = xmlNode.getChildNodes();
		for (int i=0; i<childNodes.getLength(); i++)
		{
			Node node = childNodes.item(i);
			if (node.getNodeName().equals("publisher")) parsePublisher(node);
			if (node.getNodeName().equals("comic")) parseComic(node);
			if (node.getNodeName().equals("storyArc")) parseStoryArc(node);
		}
	}
	
	public void parsePublisher(Node node)
	{
		NamedNodeMap attr = node.getAttributes();
		Node idNode = attr.getNamedItem("id");
		String id = idNode.getNodeValue();
		
		Node nameNode = attr.getNamedItem("name");
		String name = nameNode.getNodeValue();
		
		System.out.println("Publisher: " + id + ", " + name);
		getComicService().addPublisher(name);
	}
	
	public void parseComic(Node node)
	{
		NamedNodeMap attr = node.getAttributes();
		Node idNode = attr.getNamedItem("id");
		String id = idNode.getNodeValue();
		
		Node nameNode = attr.getNamedItem("title");
		String title = nameNode.getNodeValue();

		Node completeNode = attr.getNamedItem("complete");
		
		Node orderNode = attr.getNamedItem("order");
		
		Node publisherNode = attr.getNamedItem("publisher");

		System.out.println("Comic: " + id + ", " + title);
		ComicEntity comic = getComicService().addComic(title);
		comic.setCompleted(completeNode.equals("true"));
		comic.setCurrentOrder(orderNode.equals("true"));
		if (publisherNode != null)
		{
			PublisherEntity publisher = getComicService().getPublisherById(publisherNode.getNodeValue());
			getComicService().assignPublisher(comic, publisher);
		}
	}
	
	public void parseStoryArc(Node node)
	{
		NamedNodeMap attr = node.getAttributes();
		Node idNode = attr.getNamedItem("id");
		String id = idNode.getNodeValue();
		
		Node nameNode = attr.getNamedItem("title");
		String title = nameNode.getNodeValue();

		System.out.println("StoryArc: "+ id + ", " + title);
		getComicService().addStoryArc(title);
	}

	private ComicService getComicService()
	{
		return null;
	}
}
