import whatap.value.map_value as map_value
import whatap.value.list_value as list_value
from whatap.value.decimal_value import DecimalValue
from whatap.value.text_value import TextValue
import sys, traceback, os, threading
import psutil

def getAll():
    mv = map_value.MapValue()
    idlist = list_value.ListValue()
    namelist = list_value.ListValue()
    cpulist = list_value.ListValue()
    statlist = list_value.ListValue()

    for pthread in threading.enumerate():
        idlist.addLong(int(pthread.ident))
        namelist.addString(pthread.name)
        cpulist.addLong(0)
        if pthread.is_alive():
            statlist.addString("Alive")
        else:
            statlist.addString("Dead")

    mv.put("id", idlist)
    mv.put("name", namelist)
    mv.put("cpu", cpulist)
    mv.put("stat", statlist)

    return mv

def getThreadDetail(threadid):
    m = map_value.MapValue()

    if threadid in sys._current_frames():
        frame = sys._current_frames()[threadid]
        cpu_user =0
        cpu_total = 0

        m.put("Thread Id", DecimalValue(int(threadid)));
        m.put("Thread Cpu Time",  DecimalValue(cpu_total));
        m.put("Thread User Time",  DecimalValue(cpu_user));
        m.put("Blocked Count",  DecimalValue(0))
        m.put("Blocked Time",  DecimalValue(0))
        m.put("Waited Count",  DecimalValue(0))
        m.put("Waited Time",  DecimalValue(0))
        m.put("Lock Owner Id",  DecimalValue(0))
        m.put("Lock Name",  TextValue(''))
        m.put("Lock Owner Name",  TextValue(''))
        m.put("Thread Name",  TextValue(str(threadid)))

        m.put("State",  TextValue(''))

        formatted_lines = "\n".join(traceback.format_list(
            traceback.extract_stack(frame)))
        m.put("Stack Trace", TextValue(formatted_lines));

    return m