import Foundation final class RDEPUBReaderLocationCoordinator { private unowned let context: RDEPUBReaderContext init(context: RDEPUBReaderContext) { self.context = context } @discardableResult func restoreReadingLocation(_ location: RDEPUBLocation, animated: Bool = false) -> Bool { guard let controller = context.controller, let readerView = context.readerView else { return false } guard let targetPageNumber = controller.pageNumber(for: location) else { readerView.transitionToPage(pageNum: 0) context.readingSession?.transition(to: .idle) return false } if context.textBook == nil { _ = context.readingSession?.queueNavigation( to: location, relativeToSpineIndex: nil, bookIdentifier: context.currentBookIdentifier ) } else { context.readingSession?.transition(to: .jumping) } readerView.transitionToPage(pageNum: max(targetPageNumber - 1, 0), animated: animated) return true } func currentVisibleLocation() -> RDEPUBLocation? { guard let controller = context.controller, let readerView = context.readerView else { return nil } if context.textBook != nil, readerView.currentPage >= 0 { return controller.resolvedTextLocation(forPageNumber: readerView.currentPage + 1) } return context.readingSession?.currentReadingLocation(bookIdentifier: context.currentBookIdentifier) } func persistenceLocation() -> RDEPUBLocation? { guard let controller = context.controller, let currentBookIdentifier = context.currentBookIdentifier else { return nil } return controller.persistence?.loadLocation(for: currentBookIdentifier) } func persist(location: RDEPUBLocation) { guard let controller = context.controller, let currentBookIdentifier = context.currentBookIdentifier else { return } controller.persistence?.saveLocation(location, for: currentBookIdentifier) controller.delegate?.epubReader(controller, didUpdateLocation: location) controller.delegate?.epubReader(controller, didUpdateCurrentTableOfContentsItem: controller.currentTableOfContentsItem) controller.updateBookmarkChrome() } }