from xlte.amari import kpi as amari_kpi
from xlte import kpi
import io

def load_measurements(alogm):
  mlog = kpi.MeasurementLog()
  try:
    measurement = alogm.read()
    while measurement is not None:
      mlog.append(measurement)
      measurement = alogm.read()
  finally:
    alogm.close()
  return mlog

def calc_periods(mlog, tperiod):
  t = mlog.data()[0]['X.Tstart']
  for measurement in mlog.data()[1:]:
    t_ = measurement['X.Tstart']
    if (t_ - t) >= tperiod:
      calc = kpi.Calc(mlog, t, t + tperiod)
      t = calc.tau_hi
      yield calc

def getOrsKpiValues(data):
  fxlog = io.StringIO(data)
  alogm = amari_kpi.LogMeasure(fxlog,  open('/dev/null', 'r'))
  mlog = load_measurements(alogm)

  vt = []
  v_initial_epsb_estab_sr = []
  v_added_epsb_estab_sr = []

  tperiod = 60 # seconds 
  for calc in calc_periods(mlog, tperiod):
    vt.append(calc.tau_lo)
    erab_accessibility = calc.erab_accessibility()
    v_initial_epsb_estab_sr.append((erab_accessibility[0]['lo'], erab_accessibility[0]['hi']))
    v_added_epsb_estab_sr.append((erab_accessibility[1]['lo'], erab_accessibility[1]['hi']))

  evt = []
  v_ip_throughput_qci = []

  tperiod = 3 # seconds
  for calc in calc_periods(mlog, tperiod):
    evt.append(calc.tau_lo)
    eutran_ip_throughput = calc.eutran_ip_throughput()
    period_qci_data = []
    for qci, qci_measurement in enumerate(eutran_ip_throughput):
      period_qci_data.append((qci, qci_measurement['dl']['lo'], qci_measurement['dl']['hi'], qci_measurement['ul']['lo'], qci_measurement['ul']['hi']))
    v_ip_throughput_qci.append(period_qci_data)

  return vt, v_initial_epsb_estab_sr, v_added_epsb_estab_sr, evt, v_ip_throughput_qci
