package com.peetz.kontor.data;

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

import com.peetz.library.entity.BookEntity;
import com.peetz.library.service.LibraryService;

public class ImportLibrary
{
	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("book")) parseBook(node);
			if (node.getNodeName().equals("article")) parseArticle(node);
			if (node.getNodeName().equals("shelf")) parseShelf(node);
		}
	}

	public void parseBook(Node node)
	{
		NamedNodeMap attr = node.getAttributes();
		Node idNode = attr.getNamedItem("id");
		String id = idNode.getNodeValue();
		
		Node titleNode = attr.getNamedItem("title");
		String title = titleNode.getNodeValue();
		
		Node authorNode = attr.getNamedItem("author");
		String author = authorNode.getNodeValue();
		
		Node publisherNode = attr.getNamedItem("publisher");
		String publisher = publisherNode.getNodeValue();
		
		Node isbnNode = attr.getNamedItem("isbn");
		String isbn = isbnNode.getNodeValue();
		
		Node pagesNode = attr.getNamedItem("pages");
		String pages = pagesNode.getNodeValue();
		
		Node editionNode = attr.getNamedItem("edition");
		String edition = editionNode.getNodeValue();
		
		System.out.println("Book: " + id + ", " + title);
		BookEntity book = getLibraryService().addBook(title);
		book.setAuthor(author);
		book.setPublisher(publisher);
		book.setIsbn(isbn);
		book.setPage(Long.valueOf(pages));
		book.setEdition(edition);
		getLibraryService().saveBook(book);
	}
	
	public void parseArticle(Node node)
	{
		NamedNodeMap attr = node.getAttributes();
		Node idNode = attr.getNamedItem("id");
		String id = idNode.getNodeValue();
		
		Node titleNode = attr.getNamedItem("title");
		String title = titleNode.getNodeValue();
		
		System.out.println("Article: " + id + ", " + title);
		getLibraryService().addArticle(title);
	}
	
	public void parseShelf(Node node)
	{
		NamedNodeMap attr = node.getAttributes();
		Node idNode = attr.getNamedItem("id");
		String id = idNode.getNodeValue();
		
		Node titleNode = attr.getNamedItem("title");
		String title = titleNode.getNodeValue();
		
		System.out.println("Shelf: " + id + ", " + title);
		getLibraryService().addBookshelf(title);
	}
	
	private LibraryService getLibraryService()
	{
		return null;
	}
}
