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_info', renderer='json', permission='Lock Date')
@TryCatchFunction
def set_lock_info(request):
    start_locked = request.json_body['Start']['Locked']
    finish_locked = request.json_body['Finish']['Locked']
    data = {'Start': {'Locked': start_locked}, 'Finish': {'Locked': finish_locked}}

    if start_locked:
        rolling = request.json_body['Start']['Rolling']
        data['Start']['Rolling'] = rolling
        if rolling:
            data['Start']['Days'] = request.json_body['Start']['Days']
        else:
            data['Start']['Date'] = datetime.datetime.strptime(request.json_body['Start']['Date'], '%d-%b-%Y')
    if finish_locked:
        rolling = request.json_body['Finish']['Rolling']
        data['Finish']['Rolling'] = rolling
        if rolling:
            data['Finish']['Days'] = request.json_body['Finish']['Days']
        else:
            data['Finish']['Date'] = datetime.datetime.strptime(request.json_body['Finish']['Date'], '%d-%b-%Y')

    lock_date = DbSetting.by_name('Lock Info')
    if lock_date is not None:
        lock_date.data = data
    else:
        lock_date = DbSetting(name='Lock Info', data=data)
        DBSession.add(lock_date)
    transaction.commit()
    return get_lock_info(request)


@view_config(request_method='DELETE', route_name='api_lock_info', renderer='json', permission='Lock Date')
@TryCatchFunction
def clear_lock_info(request):
    lock_date = DbSetting.by_name('Lock Info')
    if lock_date is not None and lock_date.data is not None:
        lock_date.data = None
    transaction.commit()
    return {}


@view_config(request_method='GET', route_name='api_lock_info', renderer='json', permission='Authenticated')
def get_lock_info(request):
    data = DbSetting.by_name('Lock Info')
    if data is None:
        return {'Start': {'Locked': False}, 'Finish': {'Locked': False}}
    data = data.data
    info = {'Start': {'Locked': data['Start']['Locked']}, 'Finish': {'Locked': data['Finish']['Locked']}}
    if data['Start']['Locked']:
        info['Start']['Rolling'] = data['Start']['Rolling']
        if data['Start']['Rolling']:
            info['Start']['Days'] = data['Start']['Days']
        else:
            info['Start']['Date'] = data['Start']['Date'].strftime('%d-%b-%Y')

    if data['Finish']['Locked']:
        info['Finish']['Rolling'] = data['Finish']['Rolling']
        if data['Finish']['Rolling']:
            info['Finish']['Days'] = data['Finish']['Days']
        else:
            info['Finish']['Date'] = data['Finish']['Date'].strftime('%d-%b-%Y')
    return info
