# libgo - script to build library.gnome.org
# Copyright (C) 2007-2010  Frederic Peters
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301  USA

import urllib
import os
import sys
from pysqlite2 import dbapi2 as sqlite
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'src'))

from django.conf import settings
from config import Config

from django.http import HttpResponse, HttpResponseRedirect

sqlcon = None

def get_sqlconn():
    global sqlcon
    if sqlcon and False:
        return sqlcon
    config = Config(filename=settings.LIBRARY_WEB_CONFIG_FILE)
    sqlcon = sqlite.connect(config.symbols_sqlite_filepath, isolation_level=None)
    return sqlcon


def lookup(request):
    sqlcon = get_sqlconn()
    symbol = request.path_info.split('/')[-1]
    cur = sqlcon.cursor()
    cur.execute('select symbol from symbols where symbol like ? escape "\\" '
                'order by symbol limit 50',
                ('%' + symbol.replace('\\', '\\\\').replace('_', '\\_') + '%',))
    response = '\n'.join([x[0] for x in cur.fetchall()])
    cur.close()
    return HttpResponse(response, mimetype="text/plain")

def redirect(request):
    try:
        symbol = request.REQUEST['q']
    except KeyError:
        return HttpResponseRedirect('/')
    sqlcon = get_sqlconn()
    cur = sqlcon.cursor()
    cur.execute('select path from symbols where symbol = ? limit 1', (symbol,))
    path = cur.fetchone()
    if path:
        path = path[0]
        return HttpResponseRedirect(path)
    # fallback to a Google search
    return HttpResponseRedirect(
            'http://www.google.com/custom?'\
            'domains=library.gnome.org&'\
            'sitesearch=library.gnome.org&'\
            'q=%s' % urllib.quote(symbol))
