let fs = require("fs");
let JSZip  = require('jszip');
let EpubWriter = require('../src/epub')
let zip = new JSZip()
let epub = new EpubWriter()

new JSZip.external.Promise((resolve, reject)=>{
    fs.readFile('test/mythical_man_month__the__essays_on_software_engineering__anniversary_edition.zip',
    (err, data)=>{
        if (err){
            reject(err);
        } else {
            resolve(data);
        }
    })
})
.then((data)=>{
    return JSZip.loadAsync(data, {
        checkCRC32: true
    })
})
.then((zip)=>{
    return loadBookInfo(zip)
    .then((book_info)=>{
        createEbook(epub, book_info)
        return copyContent(epub, zip)
    })
    .then(()=>{
        return epub.generateAsync()
    })
    .then((file)=>{
        fs.writeFile('ttttest.epub', file, (err) => {
            if (err)
                return console.log(err);
          })
    })
})
.catch((reason)=>{
    console.log(`Error: ${reason}`)
})

function copyContent(epub, zip)
{
    let jobs = []
    zip.folder('EPUB').forEach((fileName, zipObj)=>{
        console.log(`${fileName}`)
        jobs.push(
            zipObj.async('uint8array')
            .then((buffer)=>{
                epub.addFile(fileName, buffer)
            })
        )
    })
    return Promise.all(jobs)
}

function loadBookInfo(zip)
{
    let book_json = zip.file('EPUB/book.json')
    if (!book_json){
        book_json = zip.file('META-INF/book.json')
    }
    return book_json.async('string')
            .then((blob)=>{
                return JSON.parse(blob)
            })
}

function createEbook(epub, book_info)
{
    console.log(`${book_info}`)

    //  OPF file info.
    fillManifest(epub, book_info)
    fillSpine(epub, book_info)
    fillGuide(epub, book_info)
    fillMetadata(epub, book_info)

    //  NCX and NAV files.
    fillToc(epub, book_info)
}

function fillMetadata(epub, book_info)
{
    epub.meta.addTitle(book_info.book_info.title)
    epub.meta.addLanguage(book_info.book_info.language)
    epub.meta.addBookId(book_info.book_info.isbn)
    for (let i in book_info.book_info.authors){
        let author = book_info.book_info.authors[i]
        epub.meta.addAuthor(author)
    }
    for (let i in book_info.book_info.publishers){
        let publisher = book_info.book_info.publishers[i]
        epub.meta.addPublisher(publisher.name)
    }
    // # The metadata element or deprecated dc-metadata element contains
    // # at least one identifier element, at least one title element,
    // # and at least one language element drawn from the Dublin Core tag
    // # set.
    // epub.set_title('Test Title')
    // epub.set_language('en')
    // epub.set_direction('ltr')
    // # epub.set_cover(file_name, content, create_page=True):
    // # epub.add_author(author, file_as=None, role=None, uid='creator'):
    // # epub.add_metadata(namespace, name, value, others=None):
    // # epub.set_unique_metadata(namespace, name, value, others=None):

}

function fillManifest(epub, book_info)
{
    for (let key in book_info.book_files){
        let f = book_info.book_files[key]
        epub.meta.addManifest(f.filename, f.mime)
    }

    let f = book_info.book_files[book_info.book_info.cover]
    epub.meta.addCover(f.filename)
}

function fillToc(epub, book_info)
{
    for (let i in book_info.book_toc){
        let toc_item = book_info.book_toc[i]
        epub.meta.addToc(
                    toc_item.filename,
                    toc_item.label,
                    toc_item.depth)
    }
}

function fillSpine(epub, book_info)
{
    for (let i in book_info.book_info.chapters){
        let s = book_info.book_info.chapters[i].split('/')
        epub.meta.addSpine(s[s.length-1])
    }
}

function fillGuide(epub, book_info)
{}