"use strict";
var reader;
var id = document.location.pathname.split('/')[1];
var annotations = [];
var currentSelection;
var fontSize = parseInt(localStorage.epubFontSize || '100', 10)
var justSelected = false;

Ox.load({
    'UI': {
        loadCSS: false
    }
}, function() {
    Ox.$parent.bindMessage(function(data, event) {
        console.log('got', event, 'data', data)
        if (event == 'selectAnnotation') {
            selectAnnotation(data.id)
            var annotation = annotations.filter(function(a) { return a.id == data.id })[0]
            if (annotation) {
                reader.rendition.display(annotation.cfiRange)
            }
        } else if (event == 'addAnnotation') {
            createAnnotation()
        } else if (event == 'addAnnotations') {
            if (data.replace) {
                annotations.forEach(function(a) {
                    reader.rendition.annotations.remove(a.cfiRange)
                })
                annotations = []
            }
            data.annotations.forEach(function(annotation) {
                annotations.push(annotation)
                renderAnnotation(annotation)
            })
        } else if (event == 'removeAnnotation') {
            removeAnnotation(data.id)
        }
    })
})


function createAnnotation() {
    console.log('createAnnotation', currentSelection)
    if (currentSelection) {
        /*
        var range = currentSelection.contents.window.getSelection().getRangeAt(0)
        console.log(
            currentSelection.cfiRange,
            reader.rendition.book.section().cfiFromRange(range).toString()
        )
        //currentSelection.cfiRange = reader.rendition.book.section().cfiFromRange(range).toString()
        */
        renderAnnotation(currentSelection)
        currentSelection.contents.window.getSelection().removeAllRanges();
        delete currentSelection.contents
        addAnnotation(currentSelection)
        document.querySelectorAll('.epubjs-hl.selected').forEach(function(other) {
            other.classList.remove('selected')
        })
        console.log('create annot')
        currentSelection = null
    }
}

function addAnnotation(annotation) {
    annotations.push(annotation)
    Ox.$parent.postMessage('addAnnotation', annotation)
}

function selectAnnotation(id) {
    $('.epubjs-hl.selected').each(function(i, g) {
        g.classList.remove('selected')
    })
    $('.epubjs-hl[data-id='+id+']').each(function(i, g) {
        g.classList.add('selected')
    })
}

function deselectAnnotation(id) {
    $('.epubjs-hl[data-id='+id+']').each(function(i, g) {
        g.classList.remove('selected')
    })
}


function deselectAllAnnotations() {
    var ids = []
    document.querySelectorAll('.epubjs-hl.selected').forEach(function(g) {
        g.classList.remove('selected')
        if (!Ox.contains(ids, id)) {
            ids.push(id)
            Ox.$parent.postMessage('selectAnnotation', {id: null})
        }
    })
}

function removeAnnotation(id) {
    var a = annotations.filter(function(a) { return a.id == id })[0]
    if (a) {
        annotations = annotations.filter(function(annotation) {
            return annotation.id != id
        })
        reader.rendition.annotations.remove(a.cfiRange)
    }
    Ox.$parent.postMessage('removeAnnotation', {id: id})
}

function renderAnnotation(annotation) {
    reader.rendition.annotations.highlight(annotation.cfiRange, {id: annotation.id}, onHighlightClicked);
}

function getText(book, cfiRange, cb) {
    book.getRange(cfiRange).then(function (range) {
        var text;
        if (range) {
            text = range.toString();
        }
        cb(text)
    })
}

function onHighlightClicked(e) {
    console.log("highlight clicked", e.target.dataset.epubcfi);
    if(!e.target.classList.contains('selected')) {
        document.querySelectorAll('.epubjs-hl.selected').forEach(function(other) {
            other.classList.remove('selected')
        })
        e.target.classList.add('selected')
        Ox.$parent.postMessage('selectAnnotation', {id: e.target.dataset.id})
    }
}

document.onreadystatechange = function () {
    if (document.readyState == "complete") {
        EPUBJS.filePath = "/static/epub.js/js/libs/";
        EPUBJS.cssPath = "/static/epub.js/css/";
        EPUBJS.core.addCss('/static/css/epub.css')
        // fileStorage.filePath = EPUBJS.filePath;
        reader = ePubReader(document.location.pathname, {
            restore: true
        });
        var rendition = reader.rendition,
            book = reader.book;

        rendition.themes.fontSize(fontSize + "%");

        reader.rendition.on('keydown', function(event) {
            if (event.key == 'Delete') {
                document.querySelectorAll('.epubjs-hl.selected').forEach(function(a) {
                    removeAnnotation(a.dataset.id)
                })
            }
            if (event.key == 'n' || event.keyCode == 13) {
                var selected = document.querySelector('.epubjs-hl.selected')
                console.log('!!', currentSelection, selected)

                if (currentSelection) {
                    if (selected) {
                        deselectAllAnnotations()
                    }
                    createAnnotation()
                } else if (selected) {
                    console.log('editNote?', selected.dataset.id)
                }
            }
            if (event.keyCode == 61 && event.shiftKey) {
                fontSize += 10
                rendition.themes.fontSize(fontSize + "%");
                localStorage.epubFontSize = fontSize
                event.preventDefault()
            } else if (event.keyCode == 173 && event.shiftKey) {
                fontSize -= 10
                rendition.themes.fontSize(fontSize + "%");
                localStorage.epubFontSize = fontSize
                event.preventDefault()
            } else if (event.keyCode == 48 && event.shiftKey) {
                fontSize = 100
                rendition.themes.fontSize(fontSize + "%");
                localStorage.epubFontSize = fontSize
                event.preventDefault()
            }
        }).on('mouseup', function(event) {
            if (!justSelected) {
                var selection = window.getSelection()
                if (selection.isCollapsed) {
                    currentSelection = null
                }
                if (!currentSelection) {
                    Ox.$parent.postMessage('selectText', false)
                }
            }
            deselectAllAnnotations()
            justSelected = false
        })
        rendition.on("mark", function(cfiRange, contents) {
            console.log('!! mark', cfiRange)
        })
        rendition.on("selected", function(cfiRange, contents) {
            justSelected = true
            getText(book, cfiRange, function(text) {
                var position = cfiRange;
                currentSelection = {
                    id: Ox.SHA1(cfiRange),
                    cfiRange: cfiRange,
                    position: position,
                    text: text,
                    contents: contents
                }
                Ox.$parent.postMessage('selectText', text ? true : false)
            })
        });
    }
};
