from datetime import date
from functools import lru_cache
from markdown2 import markdown
import os
from pathlib import Path
import re
import yaml


here = Path(__file__).resolve().parent
project_dir = here.parent


def get_data_dir():
    env_name = 'DATA_DIR'
    if os.environ.get(env_name):
        data_dir = Path(os.environ[env_name])
    else:
        data_dir = project_dir / 'data'
    if not data_dir.is_dir():
        raise Exception('Data directory is not a directory: {}'.format(data_dir))
    return data_dir


def load_events():
    global _cached_events
    event_dir = get_data_dir() / 'events'
    events = []
    for event_path in event_dir.iterdir():
        if event_path.name.startswith('.') or not event_path.name.endswith('.yaml'):
            continue
        try:
            events.append(_load_event(event_path))
        except Exception as e:
            raise Exception('Failed to load event from {}: {}'.format(event_path, e)) from e
    return sorted(events, key=lambda ev: ev['date'], reverse=True)


def _load_event(event_path):
    data = yaml.load(event_path.read_text())['event']
    return {
        'title': data['title'],
        'location': data.get('location'),
        'date': _to_date(data['date']) if data.get('date') else None,
        'description_html': markdown_to_html(data['description']) if data.get('description') else None,
    }


@lru_cache()
def markdown_to_html(text):
    return markdown(
        text,
        extras=[
            "link-patterns",
        ],
        link_patterns=[
            (re.compile(r'(https?:\/\/[^ \t\n]+)'), r'\1'),
        ])


def _to_date(value):
    if isinstance(value, date):
        return value
    else:
        # pravděpodobně bude stačit sem jen něco přidat
        # YAML jinak umí date interpretovat sám
        raise Exception('Not a date: {!r}'.format(value))

@@ -224,24 +224,196 @@
 data_dir():%0A
+    '''%0A    Get path to data dir - from DATA_DIR env variable (used in production) or simply%0A    from project path (in development mode, works for pip install -e).%0A    '''%0A
     env_name
@@ -716,153 +716,148 @@
     
-global _cached_events%0A    event_dir = get_data_dir() / 'events'%0A    events = %5B%5D%0A    for event_path in event_dir.iterdir():%0A        if event_path.
+'''%0A    Load all events from data/events/*.yaml%0A    '''%0A    event_dir = get_data_dir() / 'events'%0A    is_event_file_name = lambda name: not 
 name
@@ -877,26 +877,12 @@
 .') 
-or not event_path.
+and 
 name
@@ -903,218 +903,97 @@
 ml')
-:
 %0A    
-        continue%0A        try:%0A            events.append(_load_event(event_path))%0A        except Exception as e:%0A            raise Exception('Failed to load event from %7B%7D: %7B%7D'.format(event_path, e)) from e
+events = %5B_load_event(p) for p in event_dir.iterdir() if is_event_file_name(p.name)%5D
 %0A   
@@ -1087,16 +1087,80 @@
 _path):%0A
+    '''%0A    Load event data from YAML file%0A    '''%0A    try:%0A    
     data
@@ -1205,16 +1205,20 @@
 event'%5D%0A
+    
     retu
@@ -1230,16 +1230,20 @@
         
+    
 'title':
@@ -1258,16 +1258,20 @@
 itle'%5D,%0A
+    
         
@@ -1312,16 +1312,20 @@
         
+ 
+   
 'date': 
@@ -1386,16 +1386,20 @@
         
+  
+  
 'descrip
@@ -1410,16 +1410,17 @@
 _html': 
+_
 markdown
@@ -1491,17 +1491,137 @@
 ne,%0A    
+ 
-%7D
+   %7D%0A    except Exception as e:%0A        raise Exception('Failed to load event from %7B%7D: %7B%7D'.format(event_path, e)) from e
 %0A%0A%0A@lru_
@@ -1632,16 +1632,17 @@
 e()%0Adef 
+_
 markdown

Clean up model.py