import datetime

from pyramid.view import view_config
import transaction
from brewman.models import DBSession

from brewman.models.master import DbSetting
from brewman.models.validation_exception import TryCatchFunction


@view_config(route_name='settings', renderer='brewman:templates/angular_base.mako', permission='Authenticated')
def html(request):
    return {}


@view_config(request_method='POST', route_name='api_lock_date', request_param='Date', renderer='json',
             permission='Lock Date')
@TryCatchFunction
def set_lock_date(request):
    date = datetime.datetime.strptime(request.GET['Date'], '%d-%b-%Y')
    lock_date = DbSetting.by_name('Lock Date')
    if lock_date is not None:
        lock_date.data = date
    else:
        lock_date = DbSetting(name='Lock Date', data=date)
        DBSession.add(lock_date)
    transaction.commit()
    return {'Lock Date': date.strftime('%d-%b-%Y')}


@view_config(request_method='POST', route_name='api_lock_date', request_param='Clear', renderer='json',
             permission='Lock Date')
@TryCatchFunction
def clear_lock_date(request):
    lock_date = DbSetting.by_name('Lock Date')
    if lock_date is not None and lock_date.data is not None:
        lock_date.data = None
    transaction.commit()
    return {'Lock Date': ''}


@view_config(request_method='GET', route_name='api_lock_date', renderer='json', permission='Authenticated')
def get_lock_date(request):
    lock_date = DbSetting.by_name('Lock Date')
    if lock_date is not None and lock_date.data is not None:
        return {'Lock Date': lock_date.data.strftime('%d-%b-%Y')}
    return {'Lock Date': ''}
