from templess import templess
import urllib
import httplib
from cgi import escape

addtemplate = templess.template("""\
<add xmlns:t="http://johnnydebris.net/xmlns/templess">
  <doc t:content="docs">
    <t:tag t:replace="fields"><field t:attr="name name" t:content="content" /></t:tag>
  </doc>
</add>
""")

commitxml = u'<commit />'

def post_xml(host, port, path, xml):
    assert isinstance(xml, unicode)
    clen = len(xml)
    ctype = 'text/xml; charset=utf-8'
    conn = httplib.HTTPConnection(host, port)
    conn.request('POST', '/solr/update', xml.encode('utf-8', 'replace'),
                 {'Content-Type': ctype, 'Content-Length': clen})
    ret = conn.getresponse()
    conn.close()
    return ret.status, ret.read()

class SolrIndexer(object):
    def __init__(self, solrhost, solrport):
        self.solrhost = solrhost
        self.solrport = solrport

    def index(self, id, data):
        xml = addtemplate.unicode({'docs': [
                                    {'fields': [
                                        {'name': 'id', 'content': id},
                                        {'name': 'text', 'content': data},
                                        ]}
                                    ]})
        print 'indexing', id
        status, body = post_xml(self.solrhost, self.solrport, '/solr/update', xml)
        assert status == 200, status
        res = post_xml(self.solrhost, self.solrport, '/solr/update', commitxml)
        print 'commit', res[0]

    def search(self, query):
        url = self.solrurl + '/select?%s' + urllib2.quote(query)
        res = urllib2.urlopen(url)
        print res


