#!/usr/bin/env python
#coding=utf-8
"""
Author:         Xia Kai <xiaket@corp.netease.com/xiaket@gmail.com>
Filename:       goodreads.py
Date created:   2016-03-25 21:09
Last modified:  2016-03-31 23:53
Modified by:    Xia Kai <xiaket@corp.netease.com/xiaket@gmail.com>

Description:
it is required to install douban-client from pip:
    pip install douban-client
Changelog:

"""
import requests

from lxml import objectify

from book.etc import GOODREADS_KEY
from book.metaproviders import BookMeta


URL1 = "https://www.goodreads.com/book/isbn_to_id/%(isbn)s"
URL2 = "https://www.goodreads.com/book/show/%(book_id)s.json"


class GoodReadsBook(BookMeta):
    def load_bookinfo(self, bookinfo):
        self.title = bookinfo.title
        self.authors = [node.name for node in bookinfo.authors.getchildren()]
        self.pages = bookinfo.num_pages
        self.publisher = bookinfo.publisher
        self.pubdate = "%s-%s-%s" % (
            bookinfo.publication_year, bookinfo.publication_month,
            bookinfo.publication_day,
        )
        self.goodreads_id = bookinfo.id
        self.goodreads_rating = bookinfo.average_rating
        self.goodreads_url = bookinfo.url
        self.isbn10 = bookinfo.isbn
        self.isbn13 = bookinfo.isbn13
        self.cover_url = bookinfo.image_url

def get_bookinfo_by_isbn(isbn):
    response = requests.get(
        URL1 % {'isbn': isbn}, params={'key': GOODREADS_KEY},
    )
    book_id = response.text
    response = requests.get(
        URL2 % {'book_id': book_id}, params={'key': GOODREADS_KEY},
    )
    xml_obj = objectify.fromstring(response.text.encode("UTF8"))
    return GoodReadsBook(xml_obj.book)
