# -*- coding: utf-8 -*-
__author__ = 'hzp'
import threading
import time
import requests
import simplejson

import common


class BaseReporter(object):
    STATUS_OK = "ok"
    STATUS_FAILED = "failed"
    STATUS_DEPENDENCY_ERROR = "dependency error"
    STATUS_NOT_BEGIN = "not begin"

    """
    上报数据的类, 线程安全
    """
    def __init__(self, total_task, org, ip, uc_server):
        """
        初始化
        :param total_task: task总数
        :param org: org
        :param ip: 当前ip
        :param uc_server: uc服务器地址(ip:port)
        :return:
        """
        self._total_task = total_task
        self._current_task = 0
        self._lock = threading.Lock()
        self._org = int(org)
        self._ip = ip
        self._report_uri = "/api/v1/report"
        self._uc_server = uc_server

    def finish_task(self, start_time, status, msg, data=None):
        with self._lock:
            self._current_task += 1
        event = self._format_event(start_time, status, msg, data)
        self._report(event)

    def report_no_task(self):
        event = self._format_event(int(time.time()), BaseReporter.STATUS_OK, "No task", {})
        event["current"] = 1
        event["total"] = 1
        self._report(event)

    def _report(self, event):
        """
        上报json数据
        :param msg:
        :return:
        """
        report_url = "http://{0}{1}".format(self._uc_server, self._report_uri)
        data = requests.post(report_url, json=event)
        common.uclogger.info("url: {0}, data: {1}".format(report_url, data.content))
        data_obj = simplejson.loads(data.content)
        if data_obj['code'] != 0:
            return False
        return True

    def _format_event(self, start_time, status, msg, data):
        event = {
            "org": self._org,
            "ip": self._ip,
            "start_time": int(start_time),
            "end_time": int(time.time()),
            "status": status,
            "msg": msg,
            "current": self._current_task,
            "total": self._total_task
        }
        return event
