import json
import time

from aliyun.log import LogClient, LogItem, PutLogsRequest

from base import Queue, logger
from cobweb import setting


class LoghubDot:

    def __init__(self):
        self.client = LogClient(**setting.LOGHUB_CONFIG)
        self.queue = Queue()

    def build(self, topic, **kwargs):

        temp = {}
        log_item = LogItem()
        for key, value in kwargs.items():
            if not isinstance(value, str):
                temp[key] = json.dumps(value, ensure_ascii=False)
            else:
                temp[key] = value
        contents = sorted(temp.items())
        log_item.set_contents(contents)
        # log_items.append(log_item)
        # request = PutLogsRequest(
        #     project="databee-download-log",
        #     logstore="log",
        #     topic=topic,
        #     logitems=log_items,
        #     compress=True
        # )
        self.queue.push((topic, log_item), direct_insertion=True)
        # self.client.put_logs(request=request)

    def build_run(self):
        while True:
            if self.queue.length < 1000:
                time.sleep(0.5)
                continue
            try:
                log_item_info = {}
                for _ in range(1000):
                    topic, item = self.queue.pop()
                    if not item:
                        break
                    log_item_info.setdefault(topic, []).append(item)
                for topic, log_items in log_item_info.items():
                    request = PutLogsRequest(
                        project="databee-download-log",
                        logstore="log",
                        topic=topic,
                        logitems=log_items,
                        compress=True
                    )
                    self.client.put_logs(request=request)
            except Exception as e:
                logger.info(str(e))
