from pprint import pprint

import yaml


def parse_legacy_news_content(legacy_content):
    clear_str = '!ruby/hash:ActiveSupport::HashWithIndifferentAccess'
    content_dict = yaml.safe_load(legacy_content.replace(clear_str, ''))
    result = ''
    try:
        result = content_dict['news_content']['value']
    except KeyError:
        pass
    return result


def parse_legacy_schedule_content(legacy_content):
    initial = legacy_content

    s1 = "!ruby/object:ActionController::Parameters"
    s2 = "!ruby/hash:ActiveSupport::HashWithIndifferentAccess"

    for _ in (s1, s2):
        legacy_content = legacy_content.replace(_, "")
    content_dict = yaml.safe_load(legacy_content)

    if s1 not in initial or s2 not in initial:
        return yaml.safe_load(legacy_content)

    result = {}
    for k, v in content_dict.items():
        try:
            if v["parameters"]["afternoon"]:
                afternoon = v["parameters"]["afternoon"]["parameters"]
            else:
                afternoon = None

            if v["parameters"]["morning"]:
                morning = v["parameters"]["morning"]["parameters"]
            else:
                morning = None

            data = {"afternoon": afternoon, "morning": morning}
            result.update({k: data})
        except KeyError:
            print('--------' * 7)
            pprint(initial)
            raise KeyError

    return result
