# -*- coding: utf-8 -*-
#
# ITerativ GmbH
# http://www.iterativ.ch/
#
# Copyright (c) 2019 ITerativ GmbH. All rights reserved.
#
# Created on 2019-08-05
# @author: chrigu <christian.cueni@iterativ.ch>
from wagtail.core import hooks

from rooms.models import ModuleRoomSlug


@hooks.register('after_edit_page')
@hooks.register('after_create_page')
def do_after_page_edit(request, page):
    try:
        blocks = get_room_blocks(page)
    except AttributeError:
        return
    for block in blocks:
        if isinstance(block, tuple):
            title = block[1]['title']
        if isinstance(block, dict):
            title = block['value']['title']
        ModuleRoomSlug.objects.get_or_create(title=title)


def get_room_blocks(page):
    top_level_module_room_slug_blocks = get_block_from_stream_data(page.contents.stream_data, 'module_room_slug')
    content_list_module_room_slug_blocks = get_admin_slugs_from_content_list(page.contents.stream_data)
    return top_level_module_room_slug_blocks + content_list_module_room_slug_blocks


def get_block_from_stream_data(stream_data, block_name):
    if isinstance(stream_data[0], tuple):
        return [block for block in stream_data if block[0] in [block_name]]
    if isinstance(stream_data[0], dict):
        return [block for block in stream_data if block['type'] in [block_name]]
    return []


def get_admin_slugs_from_content_list(stream_data):
    module_room_slug_blocks = []
    content_list_items = get_block_from_stream_data(stream_data, 'content_list_item')
    for content_list_item in content_list_items:
        stream_data = None
        if isinstance(content_list_item, tuple):
            stream_data = content_list_item[1]
        if isinstance(content_list_item, dict):
            stream_data = content_list_item['value']
        module_room_slug_blocks = module_room_slug_blocks + get_block_from_stream_data(stream_data,
                                                                           'module_room_slug')
    return module_room_slug_blocks
