from bson.objectid import ObjectId
from staff.gap.controllers.templates import TemplatesCtl


def prepare_template_to_view(template):
    template['id'] = str(template['_id'])
    join_collection(template, 'workflows')
    join_collection(template, 'organization_ids')
    join_collection(template, 'city_ids')
    join_collection(template, 'langs')
    return template


def join_collection(template, col_name):
    template[col_name] = ','.join(str(x) for x in template[col_name]) if template[col_name] else ''


def edit_template_get(template_id):
    template = TemplatesCtl().find_one({'_id': ObjectId(template_id)})
    if template:
        return prepare_template_to_view(template)


def base_new_template(data):
    result = base_edit_template(data)
    result['type'] = data['type']
    return result


def base_edit_template(data):
    return {
        'title': data['title'],
        'workflows': data['workflows'],
        'tag': data['tag'],
        'organization_ids': data['organization_ids'],
        'city_ids': data['city_ids'],
        'langs': data['langs'],
    }


def new_template_get(type, template):
    return {
        'title': '.. название ..',
        'type': type,
        'workflows': '.. absence, illness, ..',
        'tag': '.. что_нибудь_для_поиска ..',
        'organization_ids': '.. 1, 2, ..',
        'city_ids': '.. 1, 2, ..',
        'langs': '.. ru, en, ..',
        'template': template,
    }
