import re
import os
import logging.config

from load.projects.cloud.tank_client.utils import LogType
from load.projects.cloud.cloud_helper.logging import write

LOGGER = logging.getLogger('tank_client')
LOG_MAX_LENGTH = 65536


def get_log_file(test_dir, log_type):
    if log_type == LogType.TANK:
        return os.path.join(test_dir, 'tank.log')
    elif log_type == LogType.PHANTOM:
        pattern = r'phantom_[^_]*\.log'
    elif log_type == LogType.PANDORA:
        pattern = r'pandora_[^_]*\.log'
    for f in os.listdir(test_dir):
        if re.match(pattern, f):
            return os.path.join(test_dir, f)
    return


def split_data(data, slice_length=LOG_MAX_LENGTH):
    return [data[i:i+slice_length] for i in range(0, len(data), slice_length)]


def send_log(test_dir, log_type, log_group_id, job_id, token, logging_host, logging_port):
    log_file = get_log_file(test_dir, log_type)
    if log_file is None:
        LOGGER.error(f'No file for sending log for {log_type.name}')
        return
    with open(log_file) as f:
        log_data = f.read()
    split_log_data = split_data(log_data)
    response = write(log_group_id, split_log_data, f'loadtesting.log.{log_type.name.lower()}', resource_id=job_id, token=token, logging_host=logging_host, logging_port=logging_port)
    LOGGER.info(f"Logs were sent. Response: {response}")
