import json
import logging
import os
import re
import requests
import sys
import time
import uuid

from cattle import Config
from cattle import type_manager
from cattle import utils
from cattle.agent import Agent
from cattle.lock import FailedToLock
from cattle.plugins.core.publisher import Publisher
from cattle.concurrency import Queue, Full, Empty, run, spawn


PS_UTIL = False
if not sys.platform.startswith("linux"):
    import psutil
    PS_UTIL = True

log = logging.getLogger("agent")
_STAMP_TS = None


def _get_event_suffix(agent_id):
    parts = re.split('[a-z]+', agent_id)
    if len(parts) > 1:
        return ';agent=' + parts[1]
    else:
        return ';agent=' + agent_id


def _data(events, agent_id):
    event = {}
    if agent_id is not None:
        event['agentId'] = agent_id
        suffix = _get_event_suffix(agent_id)
        event['eventNames'] = [x + suffix for x in events]
    else:
        event['eventNames'] = events
    return json.dumps(event)


def _check_ts():
    stamp_file = Config.stamp()
    if not os.path.exists(stamp_file):
        return True

    ts = os.path.getmtime(stamp_file)
    global _STAMP_TS

    if _STAMP_TS is None:
        _STAMP_TS = ts

    return _STAMP_TS == ts


def _should_run(pid):
    if not _check_ts():
        return False

    if pid is None:
        return True
    else:
        if PS_UTIL: