# -*- coding: utf-8 -*-

import re


TVM_RECORD_TMPL = """            {}: {}"""
TVM_DATA_TMPL = """
    <Tvm>
        Mode: Enabled
        <AllowedSourceServiceIds>
{}
        </AllowedSourceServiceIds>
    </Tvm>
""".format(TVM_RECORD_TMPL)


def get_ids_from_string(tvm_str):
    tvm_id_re = re.compile(r'\d+')
    return tvm_id_re.findall(tvm_str)


def prepare_tvm_data(ctype, tvm_id, tvm_data=None):
    """
    Prepare tvm data using specified parameters. Can patch existing data.
    :param ctype: type str
    :param tvm_id: type str or int
    :param tvm_data: type str
    :return: type str
    """
    if not tvm_data:
        tvm_data = TVM_DATA_TMPL.format(ctype, tvm_id)
    else:
        tvm_tag_open = False
        service_ids_open = False
        ctype_found = False
        last_line_num = 0
        tvm_ids = []
        tvm_data_splited = tvm_data.split('\n')
        for line in tvm_data_splited:
            if '<Tvm>' in line:
                tvm_tag_open = True
            if '</Tvm>' in line:
                tvm_tag_open = False
            if '<AllowedSourceServiceIds>' in line:
                service_ids_open = True
            if '</AllowedSourceServiceIds>' in line:
                last_line_num = tvm_data_splited.index(line)
                service_ids_open = False
            if tvm_tag_open and service_ids_open:
                line_ctype = line.split(':')[0].strip()
                if ctype == 'prestable':
                    if line_ctype != ctype:
                        tvm_ids.extend(get_ids_from_string(line))
                    else:
                        if tvm_id in get_ids_from_string(line):
                            ctype_found = True
                        else:
                            tvm_ids.extend(get_ids_from_string(line))
                            tvm_ids.append(str(tvm_id))
                            tvm_data_splited[tvm_data_splited.index(line)] = TVM_RECORD_TMPL.format(ctype, ', '.join(list(set(tvm_ids))))
                            ctype_found = True
                else:
                    if line_ctype == ctype:
                        if tvm_id in get_ids_from_string(line):
                            ctype_found = True
                        else:
                            tvm_ids.extend(get_ids_from_string(line))
                            tvm_ids.append(tvm_id)
                            tvm_data_splited[tvm_data_splited.index(line)] = TVM_RECORD_TMPL.format(ctype, ', '.join(
                                [str(_tvm_id) for _tvm_id in tvm_ids]))
                            ctype_found = True
                    elif line_ctype == 'prestable':
                        cur_tvm_ids = get_ids_from_string(line)
                        cur_tvm_ids.append(tvm_id)
                        tvm_data_splited[tvm_data_splited.index(line)] = TVM_RECORD_TMPL.format(line_ctype, ', '.join(
                            list(set(cur_tvm_ids))))
        if not ctype_found and last_line_num:
            tvm_data_splited.insert(last_line_num, TVM_RECORD_TMPL.format(ctype, tvm_id))
        tvm_data = '\n'.join(tvm_data_splited)
    return tvm_data


def extract_tvm_data(searchproxy_config):
    """
    Separate searchproxy config and tvm_section
    :param searchproxy_config: type str
    :return: type str tvm_data and type str searchproxy_config
    """
    tvm_tag_open = False
    searchproxy_config_splited = searchproxy_config.split('\n')
    tvm_data = []
    for line in searchproxy_config_splited:
        if '<Tvm>' in line:
            tvm_tag_open = True
        if tvm_tag_open:
            tvm_data.append(line)
        if '</Tvm>' in line:
            tvm_tag_open = False
    for line in tvm_data:
        searchproxy_config_splited.remove(line)
    return '\n'.join(tvm_data), '\n'.join(searchproxy_config_splited)


def patch_searchproxy_config(searchproxy_config, tvm_data):
    """
    Patch searchproxy_config with tvm section
    :param searchproxy_config: type str
    :param tvm_data: type str
    :return: type str
    """
    searchproxy_config_splited = searchproxy_config.split('\n')
    tvm_data_splited = tvm_data.split('\n')
    for line in tvm_data_splited:
        if line:
            searchproxy_config_splited.insert(searchproxy_config_splited.index('</Service>'), line)
    return '\n'.join(searchproxy_config_splited)
