import csv
import json
import os
from glob import glob
from creole.rest_tools.clean_writer import rest2html


sheet = csv.reader(open('slides.csv'))

keys = sheet.__next__()

# get_content will remove all files we use
# and in the end of the process, only orphans
# will remain
orphans = glob('slides/*.rst')

def get_content(slide, default):
    if not slide:  # Happens for home slide
        slide = '_home'
    filename = 'slides/{}.rst'.format(slide)
    # Yes. This is a side effect. Sorry.
    if filename in orphans:
        orphans.remove(filename)
    if not os.path.isfile(filename):
        desc = default.strip()
        # if desc:
        #     desc = "**תוכן זמני:** {}".format(desc)
        open(filename, 'w').write(desc)
        print('Created {}.'.format(filename))
    return rest2html(open(filename).read())

def format_slide_param(key, value):
    return format('data-{}="{}"'.format(
        key.strip(), value.strip()))

def get_slide_params(d):
    params = []
    if d.get('theme', '').strip():
        params.append(format_slide_param('theme', d['theme'].lower()))
    if d.get('bg-image','').strip():
        params.append(format_slide_param('background-image', d['bg-image']))
        if d.get('bg-style','').strip().lower()=='tile':
            params.append(format_slide_param('background-size', 'auto'))
            params.append(format_slide_param('background-repeat', 'repeat'))
        if d.get('bg-opacity','').strip():
            params.append(format_slide_param('background-opacity', d['bg-opacity']))
    return ' '.join(params)


def main():
    col_id = None
    col = None
    cols = []
    continuation = ''
    for r in sheet:
        d = dict(zip(keys,r))
        if not d['slide'].strip(): # new column
            if col is not None: # deal with previous col
                col['has_slides'] = len(col['slides'])>0
                cols.append(col)
            col_id = d['column']
            col = {
                'id': col_id,
                'title': d['title'],
                'params': get_slide_params(d),
                'content': d['html'].strip() or get_content(col_id, d['description']),
                'has_menu': False,
                'slides': []}
        else:
            headline = d['title']
            if headline:
                continuation = headline
            else:
                headline = '{} (המשך)'.format(continuation)
            slide_id = '_'.join(filter(None, [col_id, d['slide']]))
            col['slides'].append({
                'id': slide_id,
                'title': d['title'],
                'headline': headline,
                'params': get_slide_params(d),
                'has_menu': False,
                'content': d['html'].strip() or get_content(slide_id, d['description'])})
    col['has_slides'] = len(col['slides'])>0
    cols.append(col)
    cols[0]['has_menu'] = True
    cols[0]['menu'] = [{"id": c['id'], "title": c['title']} for c in cols[1:]]
    
    json.dump({"title": cols[0]['title'], "columns": cols}, open('slides.json', 'w'), indent=4)
    print('successfully wrote slides.json')
    if orphans:
        print('Note! The following rst files are not mentioned in the csv sheet (orphans):')
        for f in sorted(orphans):
            print('    {}'.format(f))

if __name__=='__main__':
    main()
