import org.jsoup.Jsoup;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;

/**
 * Created by shumailovr on 17.12.14.
 */
public class ReadBookFile {

    public static org.jsoup.nodes.Document readBookIn(File input) {
        try {
            org.jsoup.nodes.Document book = Jsoup.parse(input, "UTF-8");
            return book;
        } catch (IOException e) {
            e.printStackTrace();
        }
        //I know this is bad practice, just returning empty documents is not so easy and I don't want to do this
        return null;
    }

    public static String readBookTitle(org.jsoup.nodes.Document book) {
        Elements bookInfoElements = book.select("pre");
        if (!bookInfoElements.isEmpty()) {
            org.jsoup.nodes.Element bookInfoElement = bookInfoElements.get(0);
            if (bookInfoElement.text().contains("Title:")) {
                int index = bookInfoElement.text().indexOf("Title:");
                int endIndex = bookInfoElement.text().substring(index + 6).indexOf("\n");
                String bookTitle = bookInfoElement.text().substring(index + 6, index + 6 + endIndex);
                bookTitle = bookTitle.trim();
                return bookTitle;
//            System.out.println(bookInfoElement.text().substring(index + 7, index + 7 + endIndex));
            }
        }
        return "";
    }

    public static String readBookAuthor(org.jsoup.nodes.Document book) {
        Elements bookInfoElements = book.select("pre");
        if (!bookInfoElements.isEmpty()) {
            org.jsoup.nodes.Element bookInfoElement = bookInfoElements.get(0);
            if (bookInfoElement.text().contains("Author:")) {
                int index = bookInfoElement.text().indexOf("Author:");
                int endIndex = bookInfoElement.text().substring(index + 7).indexOf("\n");
                String bookAuthor = bookInfoElement.text().substring(index + 7, index + 7 + endIndex);
                bookAuthor = bookAuthor.trim();
                return bookAuthor;
//            System.out.println(bookInfoElement.text().substring(index + 8, index + 8 + endIndex));
            }
        }
        return "";
    }

    /**
     * Unfortunately, in Project Gutenberg html books there is no explicit tag of "content"
     * or anything similar, "body" is closest tag to actual book content that I managed to find
     * (that would work on all gut books)
     * @param book
     * @return
     */
    public static String readBookContent(org.jsoup.nodes.Document book) {
        book.select("pre").remove();
        Elements content = book.select("body");
        if (content != null) {
            String bookContent = content.get(0).text();
            return bookContent;
        }
        return "";
    }



}
