# -*- coding: utf-8 -*-
import json
import time
import requests
import datetime
import warnings
from dateutil.parser import parse

from datacloud.dev_utils.logging.logger import get_basic_logger
from datacloud.dev_utils.tvm.tvm_utils import TVMManager
from datacloud.dev_utils.tvm import tvm_id
from datacloud.dev_utils.time.patterns import FMT_DATE

logger = get_basic_logger(__name__)
TIMESHIFT = 3 * 3600


def is_date(string):
    '''
    Checks if this string could be a date
    '''
    try:
        parse(string)
        return True
    except ValueError:
        return False


def str2ts(string, date_format=FMT_DATE):
    '''
    time conversion from '%Y-%m-%d' to %s
    '''
    return int(datetime.datetime.strptime(string, date_format).strftime('%s')) + TIMESHIFT


def post_sensors_to_solomon(project, cluster, service, sensors, wait=0.001, repeats=3):
    '''
    Function sends sensors to Solomon API with some delay
    '''
    ticket = TVMManager().get_ticket(tvm_id.DATACLOUD.prod, tvm_id.SOLOMON.prod)
    headers = {
        'Content-Type': 'application/json',
        'X-Ya-Service-Ticket': ticket.value
    }
    url = 'https://solomon.yandex.net/api/v2/push?project={}&cluster={}&service={}'.format(
        project, cluster, service
    )
    payload = json.dumps({'sensors': sensors})
    response = requests.post(url, data=payload, headers=headers)

    if response.status_code == 200:
        logger.info('Code: {}. Sent to Solomon'.format(response.status_code))
    else:
        logger.info(response)
        logger.info(response.text)
        logger.info('Code: {}. Something wrong. Request will be repeated for {} times. Next repeat in 1 second'.format(response.status_code, repeats))
        time.sleep(1)
        repeats -= 1
        if repeats > 0:
            post_sensors_to_solomon(project, cluster, service, sensors, wait, repeats)
        else:
            raise requests.exceptions.ConnectionError('Code: {}. Out of repeats.'.format(response.status_code))

    time.sleep(wait)
    return response


def get_schema(project, cluster, service):
    '''
    ATTENTION: this function is DEPRECATED in favor of post_sensors_to_solomon!

    Generates dictionary with neccesary fields to
    push send to Solomon
    '''
    warnings.warn('get_schema is deprecated!'
                  ' Use post_sensors_to_solomon!', DeprecationWarning)
    schema = {
        'commonLabels': {
            'project': project,
            'cluster': cluster,
            'service': service
        },
        'sensors': []
    }
    return schema


def post_schema_to_solomon(schema, wait=0.001, repeats=3):
    '''
    ATTENTION: this function is DEPRECATED in favor of post_sensors_to_solomon!
    '''
    warnings.warn('post_schema_to_solomon is deprecated!'
                  ' Use post_sensors_to_solomon!', DeprecationWarning)
    post_sensors_to_solomon(
        project=schema['commonLabels']['project'],
        cluster=schema['commonLabels']['cluster'],
        service=schema['commonLabels']['service'],
        sensors=schema['sensors'],
        wait=wait,
        repeats=repeats
    )


def post_sensors_to_solomon_by_batches(project, cluster, service,
                                       sensors, wait=0.001,
                                       repeats=3, batch_size=5000):
    responses = []
    for i in range(0, len(sensors)/batch_size + 1):
        responses.append(post_sensors_to_solomon(
            project,
            cluster,
            service,
            sensors[i * batch_size:(i + 1) * batch_size],
            wait,
            repeats
        ))
    return responses

if __name__ == '__main__':
    sensors = [{'ts': 1535979498, 'value': 100, 'labels': {'test_label': 'test_aaaaaaAA'}}]
    post_sensors_to_solomon('datacloud', 'money', 'by-5min-logs', sensors, wait=0.001, repeats=10)
