# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, division, absolute_import, print_function)
__my_version__ = "3.6.43"

import sys, BaseHTTPServer, urllib, urlparse, xml.dom.pulldom, xml.dom.minidom, cgi, socket, xml.sax.saxutils, StringIO, string, codecs, time, datetime, os
from urllib import urlencode

#------------------------------------------------------------------------------------------------------
def oclc_classify_api(paramtype,paramvalue):
    #http://classify.oclc.org/classify2/api_docs/index.html
    #http://classify.oclc.org/classify2/api_docs/classifySample.py
    # Usage: python classifySample.py <param-type> <param-value>
    # or, use stdnbr instead of isbn so it will search for any standard number (isbn, issn, upc, etc.)

    parmType = paramtype
    parmValue = paramvalue
    summaryInd = 'true'          #always True for this purpose.

    ddc_return = "NONE"
    lcc_return = "NONE"
    owi_return = "NONE"

    print('Searching for: ' + parmType + '=' + parmValue)

    base = 'http://classify.oclc.org/classify2/Classify?'
    summaryBase = '&summary=true'

    def getText(nodelist):
        rc = ""
        for node in nodelist:
            if node.nodeType == node.TEXT_NODE:
                rc = rc + node.data
        return rc

    xdoc = ''
    try:
        if summaryInd == 'true': nextURL = base + urlencode({parmType:parmValue.encode('utf-8')}) + summaryBase
        else: nextURL = base + urlencode({parmType:parmValue.encode('utf-8')})
        print(nextURL)
        urlobj = urllib.urlopen(nextURL)
        response = urlobj.read()
        urlobj.close()
        xdoc = xml.dom.minidom.parseString(response)
    except UnicodeDecodeError:
        print('UnicodeDecodeError: ' + nextURL)
    except IOError:
        print('IOError: ' + nextURL)

    response = xdoc.getElementsByTagName('response')[0]
    respCode = response.attributes["code"].value
    print('Method response: ' + respCode)
    print("---------------------------------------------------------------------------------------------------")
    if respCode == '0' or respCode == '2':
        recommendations = xdoc.getElementsByTagName('recommendations')[0]
        if recommendations:
            ddc = recommendations.getElementsByTagName('ddc')[0]
            if ddc:
                for mostPopular in ddc.getElementsByTagName('mostPopular'):
                    holdings = mostPopular.attributes["holdings"].value
                    nsfa = mostPopular.attributes["nsfa"].value
                    sfa = mostPopular.attributes["sfa"].value
                    print('DDC mostPopular: class=' + sfa + ' normalized=' + nsfa + ' holdings=' + holdings)
                    ddc_return = sfa

            lcc = recommendations.getElementsByTagName('lcc')[0]
            if lcc:
                for mostPopular in lcc.getElementsByTagName('mostPopular'):
                    holdings = mostPopular.attributes["holdings"].value
                    nsfa = mostPopular.attributes["nsfa"].value
                    sfa = mostPopular.attributes["sfa"].value
                    print('LCC mostPopular: class=' + sfa + ' normalized=' + nsfa + ' holdings=' + holdings)
                    lcc_return = sfa

        #--------------------------------------------------------
        # added by DaltonST for Q&S so as to return owi
        #--------------------------------------------------------
        try:
            work = xdoc.getElementsByTagName('work')[0]
            if work:
                author = work.attributes["author"].value
                title = work.attributes["title"].value
                try:
                    print("author(s): ", str(author))
                    print("title: ", str(title))
                except:
                    pass
                owi = work.attributes["owi"].value
                owi_return = owi
                print("owi: ", str(owi))
                print("---------------------------------------------------------------------------------------------------")
        except:
            pass
        #--------------------------------------------------------
    else:
        return ddc_return, lcc_return, owi_return


    return ddc_return, lcc_return, owi_return


#------------------------------------------------------------------------------------------------------
# example results returned and parsed using the api:
#------------------------------------------------------------------------------------------------------
'''
<?xml version="1.0" encoding="UTF-8"?>
<classify xmlns="http://classify.oclc.org">
  <response code="0"/>
  <!--Classify is a product of OCLC Online Computer Library Center: http://classify.oclc.org-->
  <work author="McGee, Harold | McGee, Harold [Author] | Cai, Chengzhi | Lin, Huizhen | Qiu, Wenbao | Ibeas Delgado, Juan Manuel," editions="74" eholdings="6" format="Book" holdings="3460" itemtype="itemtype-book" owi="572969" title="On food and cooking : the science and lore of the kitchen">10711863</work>
  <authors>
    <author lc="null" viaf="211226544">Lin, Huizhen</author>
    <author lc="n83311533" viaf="71503302">McGee, Harold [Author]</author>
    <author lc="no2008059459" viaf="14578435">Cai, Chengzhi</author>
  </authors>
  <orderBy>hold desc</orderBy>
  <input type="isbn">9780684843285</input>
  <recommendations>
    <ddc>
      <mostPopular holdings="3191" nsfa="641.5" sfa="641.5"/>
      <mostRecent holdings="3191" sfa="641.5"/>
      <latestEdition holdings="1" sf2="22" sfa="641"/>
      <latestEdition holdings="1626" sf2="22" sfa="641.5"/>
    </ddc>
    <lcc>
      <mostPopular holdings="3249" nsfa="TX651" sfa="TX651"/>
      <mostRecent holdings="3249" sfa="TX651"/>
    </lcc>
  </recommendations>
</classify>
'''
#------------------------------------------------------------------------------------------------------
#------------------------------------------------------------------------------------------------------
#------------------------------------------------------------------------------------------------------
#------------------------------------------------------------------------------------------------------
#END OF classify_web_service_api.py