#!/usr/bin/python
import os

virtenv = os.environ['APPDIR'] + '/virtenv/'
os.environ['PYTHON_EGG_CACHE'] = os.path.join(virtenv, 'lib/python2.6/site-packages')
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
try:
    execfile(virtualenv, dict(__file__=virtualenv))
except IOError:
    pass

#IMPORTANT: Put any additional includes below this line.  If placed above this
#line, it's possible required libraries won't be in your searchable path

from web import wsgiserver
import web
import utils
import ConfigParser

config = ConfigParser.RawConfigParser()
config.read(os.path.join(os.environ['OPENSHIFT_REPO_DIR'],
                         'data/squeez.cfg'))

# Base URL will be used in templates to construct the URLs.
common = {'base_url': config.get('misc', 'base_url')}
render = web.template.render(os.path.join(os.environ['OPENSHIFT_REPO_DIR'],
                                          'data/templates/'), globals=common)

# List of URLs provided by squeez.
urls = (
    '/', 'index',
    '/u/(.*)', 'unsqueez',
    '/squeez', 'squeez',
    '/squeezd/(.*)', 'squeezd',
    '/email/(.*)', 'email',
    '/sendemail', 'sendemail'
)

# Database setup using values specified in config file.
db = web.database(dbn = config.get('db', 'type'),
                  user = config.get('db', 'user'),
                  pw = config.get('db', 'pass'),
                  db = config.get('db', 'name'),
                  host = config.get('db', 'host'))

class index:
    """This is the index page of Squeez."""

    def GET(self):
        return render.index()

class unsqueez:
    """Helps to unsqueez the squeezd URL.

    HASH accepts squeezd url hash and unsqueezs it based on db lookup."""

    def GET(self, hash):
        if hash:
            result = db.query("SELECT url FROM url_mapper WHERE hash=$hash",
                              vars={'hash':hash})
            if result:
                # Redirect to the actual URL.
                raise web.redirect(result[0].url)
            else:
                # If no matches found go to given url within squeez.
                raise web.seeother(hash)
        else:
            # Don't have anything to do? Then show index!
            return render.index()

class squeez:
    """Squeezs the given URL.
    
    URL is given as an input in text box."""

    def POST(self):
        i = web.input()

        while True:
            # Retry until we have a unique hash value.
            hash = utils.get_hash()
            result = db.query("SELECT * FROM url_mapper WHERE hash=$hash",
                              vars={'hash':hash})
            if result:
                continue
            else:
                break

        # Check if the URL which we want to squeez is already available with
        # a hash value, if not then assign a new hash value.
        hash_result = db.query("SELECT hash FROM url_mapper WHERE url=$url",
                               vars={'url':i.squeez})
        if hash_result:
            hash = hash_result[0].hash
        else:
            n = db.insert('url_mapper',
                          url=i.squeez,
                          expiry=utils.get_expiry(),
                          hash=hash)

        raise web.seeother('/squeezd/' + hash)

class squeezd:
    """Page to land after squeezing a URL."""

    def GET(self, url):
        return render.squeezd(url)

class sendemail:
    """Sends email based on configuration provided above."""

    def POST(self):
        if config.get('email', 'smtp_username') == "username@gmail.com":
            return render.close("Email Configuration Unavailable!")
        else:
            i = web.input()
            web.config.smtp_server = config.get('email', 'smtp_server')
            web.config.smtp_port = config.getint('email', 'smtp_port')
            web.config.smtp_username = config.get('email', 'smtp_username')
            web.config.smtp_password = config.get('email', 'smtp_password')
            web.config.smtp_starttls = config.get('email', 'smtp_starttls')
            web.sendmail(config.get('email', 'smtp_username'), i.emailid,
                         i.subject, i.message)
            return render.close("Email sent successfully ...")

class email:
    """Page which gets content for sending email."""

    def GET(self, url):
        return render.email(url)

# Make a WSGI compliant application.
application = web.application(urls, globals(), autoreload=False).wsgifunc()

# The following is for testing locally.
if __name__ == "__main__":
    app = web.application(urls, globals())
    app.internalerror = web.debugerror
    app.run()
