#!/usr/bin/env python
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai

from __future__ import (unicode_literals, division, absolute_import, print_function)

import re

from calibre_plugins.overdrive_link.library import SearchableLibrary
from calibre_plugins.overdrive_link.formats import FORMAT_ADOBE_EPUB

__license__ = 'GPL v3'
__copyright__ = '2012-2025, John Howell <jhowell@acm.org>'


ALLOWED_LIBRARY_IDS = {
    'read',             # open 'Read' books, available to all, open access - no need to borrow
    'lendinglibrary',   # open 'Lending Library' collection, available to all
    'inlibrary',        # 'In Library' collection, restricted to library patrons (also include open lending library)
    'printdisabled',    # Accessible editions for the disabled
    }


class OpenLibrary(SearchableLibrary):
    id = 'ol'
    name = 'Open Library'
    formats_supported = {FORMAT_ADOBE_EPUB}

    @staticmethod
    def validate_library_id(library_id, migrate=True, config=None):
        if migrate and library_id == '':
            library_id = 'inlibrary'    # migrate from old plugin versions

        if library_id not in ALLOWED_LIBRARY_IDS:
            raise ValueError('Open Library library-id may only be %s, found: "%s"' % (
                ' or '.join(list(ALLOWED_LIBRARY_IDS)), library_id))

        return library_id

    @staticmethod
    def validate_book_id(book_id, library_id):
        if not re.match(r'^OL([0-9]+)[MW]$', book_id):
            #OL###W for a work (book), OL###M for an edition of a work
            raise ValueError('Open Library book id must be OL###M or OL###W: "%s"' % book_id)

        return book_id

    @staticmethod
    def book_url(library_id, book_id):
        if book_id[-1:] == 'M':
            return 'https://openlibrary.org/books/%s' % book_id   # singe edition
        if book_id[-1:] == 'W':
            return 'https://openlibrary.org/works/%s' % book_id   # work (set of editions)
        raise ValueError

    @staticmethod
    def book_key_library_id(library_id):
        return library_id   # has same book ids at all libraries, but different available formats

    def __init__(self):
        pass

    def sign_in(self, use_credentials):
        self.log.error(
            "The ability to search Open Library has been removed from this plugin."
            " Change the plugin configuration to use the Internet Archive instead.")

    def find_books(self, books, search_author, search_title, keyword_search):
        return False

    def get_book_info(self, book_id, cache):
        return None

    def get_current_book_availability(self, book_id):
        return 0
