"""
Woodstock
Copyright (C) 2010 Matteo Dello Ioio

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 3 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, see <http://www.gnu.org/licenses/>.
"""

import logging
import md5

from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect

from woodstock.lib.base import BaseController, render, Session
from woodstock.model.user import User

log = logging.getLogger(__name__)

class HomeController(BaseController):
                
    def index(self):
        return render('/home.mako')

    def sign_up(self):
        return render('/signup.mako')

    def register_user(self):
        u = User()
        u.name = request.params['name']
        u.password = request.params['password']
        u.email = request.params['email']
        u.enabled = True
        
        Session.add(u)
        Session.commit()

        redirect(url.current(action='index'))

    def login(self):
        return render('/login.mako')

    def authenticate(self):
        form_username = str(request.params.get('username'))
        form_password = str(request.params.get('password'))


        # Get user data from database
        user = Session.query(User).filter(User.name==form_username).first()

        if user is None: # User does not exist
            return render('/login.mako')

        # Wrong password? (MD5 hashes used here)
        
        #if user.password != md5.md5(form_password).hexdigest():
        if user.password != form_password:
            return "Bad authentication." #render('login.mako')

        # Mark user as logged in
        session['user'] = form_username
        session.save()

        if user.name == "admin":
            return redirect(url(controller='admin/menu', action='index'))
        else:
            return redirect(url.current(action='index'))
        """    
        if session.get('path_before_login'):
            print "AAA:"+session['path_before_login']
            redirect(session['path_before_login'])
        else: # if previous target is unknown just send the user to a welcome page
            print "OOO"            
            redirect(controller='/home', action='index')
        """
            
    def logout(self):
        if 'user' in session:
            del session['user']
            session.save()
        return redirect(url.current(action='index'))
