from __future__ import absolute_import

import cgi
import urllib

import httplib2

from .schema import SolrSchema, SolrError

h = httplib2.Http(".cache")


class SolrConnection(object):
    def __init__(self, url, h=h):
        self.url = url.rstrip("/") + "/"
        self.update_url = self.url + "update/"
        self.select_url = self.url + "select/"
        self.request = h.request

    def commit(self):
        response = self.update("<commit/>")

    def optimize(self):
        response = self.update("<optimize/>")

    def update(self, update_doc):
        body = update_doc
        headers = {"Content-Type":"text/xml; charset=utf-8"}
        r, c = self.request(self.update_url, method="POST", body=body,
                            headers=headers)
        if r.status != 200:
            raise SolrError(r, c)

    def select(self, params):
        qs = urllib.urlencode(params)
        url = "%s?%s" % (self.select_url, qs)
        r, c = self.request(url)
        if r.status != 200:
            raise SolrError(r, c)
        return c


class SolrInterface(object):
    def __init__(self, url, schemadoc):
        self.conn = SolrConnection(url)
        self.schema = SolrSchema(schemadoc)

    def add(self, docs):
        update_message = self.schema.make_update(docs)
        self.conn.update(str(update_message))

    def commit(self):
        self.conn.commit()

    def search(self, **kwargs):
        params = kwargs.copy()
        for k, v in kwargs.items():
            if hasattr(v, "items"):
                del params[k]
                params.update(v)
        return self.schema.parse_results(self.conn.select(params))

    def query(self, phrase=None):
        return SolrQuery(self, phrase)


class SolrQuery(object):
    def __init__(self, interface, phrase):
        self.interface = interface
        self.schema = interface.schema
        self.phrase = phrase
        self.filters = []

    def filter(self, **kwargs):
        for k, v in kwargs.items():
            try:
                name, rel = k.split("__")
            except ValueError:
                name, rel = k, 'eq'
            self.filters.append((name, rel, v))
            return self

    def execute(self):
        return self.interface.search(q=str(self))

    def __str__(self):
        s = [self.phrase] if self.phrase else []
        for name, rel, value in self.filters:
            s.append(" %s:%s" % (name, value))
        return ''.join(s)

@@ -1916,16 +1916,42 @@
 ers = %5B%5D
+%0A        self.options = %7B%7D
 %0A%0A    de
@@ -2223,22 +2223,402 @@
 def 
-execute(self):
+facet_by(self, field, limit=None, mincount=None):%0A        self.options.update(%7B%22facet%22:%22true%22,%0A                             %22facet.field%22:field%7D)%0A        if limit:%0A            self.options%5B%22f.%25s.facet.limit%22 %25 field%5D = limit%0A        if mincount:%0A            self.options%5B%22f.%25s.facet.mincount%22 %25 field%5D = mincount%0A        return self%0A%0A    def execute(self):%0A        self.options%5B%22q%22%5D = str(self)
 %0A   
@@ -2655,19 +2655,22 @@
 rch(
-q=str(self)
+**self.options
 )%0A%0A 

Add a facet_by function for the querier