# coding=utf-8
from __future__ import unicode_literals, print_function, absolute_import


import json
import time
import redis
from .. import settings as ds_settings
from ..core.model_event import DataChangeEvent


redis_connection = redis.from_url(ds_settings.REDIS_SERVER_URL)


def current_time():
    return time.time()


def table_event_enqueue(table_event):
    assert isinstance(table_event, DataChangeEvent)
    data = table_event.to_dict()
    timed_data = {
        'time': current_time(),
        'data': data,
    }
    timed_data_json = json.dumps(timed_data)

    if ds_settings.ENABLE_REDIS_TABLE_EVENT_QUEUE:
        redis_connection.rpush(ds_settings.REDIS_TABLE_EVENT_QUEUE_NAME, timed_data_json)
        redis_connection.publish(ds_settings.REDIS_TABLE_EVENT_CHANNEL_NAME, timed_data_json)


def parse_table_event(timed_data_json):
    timed_data = json.loads(timed_data_json)
    pushed_time = timed_data['time']
    data = timed_data['data']
    table_event = DataChangeEvent.from_dict(data)
    return current_time() - pushed_time, table_event


