from hashlib import sha1
import pickle

import settings

COOKIE_NAME_ERROR = 'flash-error'
COOKIE_NAME_NOTICE = 'flash-notice'

def flash_error(msg):
    Flash.set_error = msg

def flash_notice(msg):
    Flash.set_notice = msg

def context_processor(request):
    if COOKIE_NAME_ERROR in request.COOKIES:
        Flash.error = _decode(request.COOKIES[COOKIE_NAME_ERROR])
    elif Flash.set_error:
        Flash.error, Flash.set_error = Flash.set_error, None
        
    if COOKIE_NAME_NOTICE in request.COOKIES:
        Flash.notice = _decode(request.COOKIES[COOKIE_NAME_NOTICE])
    elif Flash.set_notice:
        Flash.notice, Flash.set_notice = Flash.set_notice, None
    
    return {'flash': Flash}

class Middleware(object):
    
    def process_request(self, request):
        Flash.clear()

    def process_response(self, request, response):
        if Flash.set_error:
            response.set_cookie(COOKIE_NAME_ERROR, _encode(Flash.set_error))
        else:
            response.delete_cookie(COOKIE_NAME_ERROR)
        if Flash.set_notice:
            response.set_cookie(COOKIE_NAME_NOTICE, _encode(Flash.set_notice))
        else:
            response.delete_cookie(COOKIE_NAME_NOTICE)
        
        return response

def _encode(value):
    value = pickle.dumps(value)
    hash = sha1(value + settings.SECRET_KEY)
    return '%s$%s' % (hash.hexdigest(), value)

def _decode(cookie):
    s = cookie.split('$', 1)
    if not s or len(s) != 2:
        return None
    hash, value = s
    if sha1(value + settings.SECRET_KEY).hexdigest() != hash:
        return None
    return pickle.loads(value)
        
class Flash(object):
    @classmethod 
    def clear(cls):
        cls.error = None
        cls.notice = None
        cls.set_error = None
        cls.set_notice = None