# smeUtils.py

#
#   def smeModuleUpdate (module):
#       Faz a releitura de um módulo local
#
#   def smeFigRectGetDims (qt):
#       Dado um número "qt" de objectos, procura as dimensões "(N, N)" ou "(N+1, N) em que
#       caibam todas os objectos
#
#   def smePrintVect (v1, qt=-1):
#       Imprime no ecrã um vector, em que "qt" pode ser um número ou uma lista de dois elementos.
#       Se for um número e "qt < 0" imprime todos os valores, no caso contrário imprime os "qt"
#       primeiros elementos. Se "qt" for uma lista de dois elementos imprime da posição qt[0]
#       até à posição "qt[1]-1".
#
#   def smePrintTwoVects (v1, v2, qt=-1, sep=" --- "):
#       Imprime dois vectores
#
#   def smeFileReadFloat (fname, skip=0, sep=' '):
#       Lê um ficheiro de floats e retorna um vector em que linha corresponde a um elemento desse vector.
#       "fname" é o nome do ficheiro, "skip" é o número de linhas iniciais a ignorar e "sep" é separador
#       entre os números
#
#   def smeTimeDiff (tInit=None):
#       Calcula o tempo de cálculo e o tempo de CPU. Para marcar o tempo inicial usa-se sem
#       argumentos; para calcular os intervalos de tempo, deve receber o valor inicial retornado.
#       O retorno é um dicionário com dois elementos: 'time' (correspondente ao tempo real) 'clock'
#       (correspondente ao tempo de CPU).
#


###############################################

def smeModuleUpdate (module="smeXXX"):
    print ("from importlib import reload")
    print (f"import {module}")
    print (f"reload({module})")
    print (f"from {module} import *")


def smeFigRectGetDims (qt):
    import numpy as np
    x = int(np.sqrt(qt))
    if qt == x*x:
        vQt = (x, x)
    else:
        vQt = (x+1, x)
    return vQt


def smeFileReadNum (fname, skip=0, sep=' ', cols=0, dType=float):
    import numpy as np

    v1 = []
    n1 = -1
    with open(fname) as f1:
        while line := f1.readline():
            n1 += 1
            if n1 < skip: continue
            if line == '': break

            line = [dType(float(x)) for x in line.strip('\n').strip().split(sep)] # if line != ''] 
            if v1 == []:
                qtCols = len(line)
                if type(cols) == int:
                    vCols = [1]*qtCols
                else:
                    n2 = -1
                    vCols = [0]*qtCols
                    while n2 < qtCols:
                        n2 += 1
                        if n2 in cols: vCols[n2] = 1

            n2 = 0
            v2 = []
            while n2 < qtCols:
                if vCols[n2] == 1: v2.append(line[n2])
                n2 += 1
            v1.append(v2)

            #v1.append(np.array([float(val) for val in line2.rstrip('\n').split(' ') if val != '']))
            #v1.append([float(val) for val in line2.rstrip('\n').split(' ') if val != ''])

        return v1


def smeFileReadNumRand (fname, skip=0, sep=' ', cols=-1, type=float, nRand=0):
    import random
    v1 = smeFileReadNum (fname, skip=skip, sep=sep, cols=cols, type=type)

    lenV1 = len(v1)
    lenV1m1 = lenV1 - 1
    if nRand <= 0 or nRand > lenV1:
        nRand = lenV1

    ptTest = [0]*lenV1
    n1 = 0
    while n1 < lenV1:
        n2 = random.randint(0, lenV1m1)
        x1 = v1[n1]
        v1[n1] = v1[n2]
        v1[n2] = x1
        n1 += 1

    if nRand < lenV1: v1 = v1[0:nRand]

    return v1
    

def smePrintVect (v1, qt=-1):
    qt2 = [0, 0]
    if type(qt) == list:
        if len(qt) < 2: return
        qt2 = qt
        if qt2[1] < 0: qt2[1] = len(v1)
    else:
        qt2[1] = (qt if qt > 0 else len(v1))
    if qt2[0] > qt2[1]: return
    
    n1 = -1
    for p in v1:
        n1 = n1 + 1
        if n1 < qt2[0]: continue
        if n1 >= qt2[1]: break
        print("[", n1, "]:", p)


def smePrintTwoVects (v1, v2, qt=-1, sep=" --- "):
    qt2 = [0, 0]
    if type(qt) == list:
        if len(qt) < 2: return
        qt2 = qt
        if qt2[1] < 0: qt2[1] = len(v1)
    else:
        qt2[1] = (qt if qt > 0 else len(v1))
    if qt2[0] > qt2[1]: return

    len1 = len(v1)
    len2 = len(v2)

    if len1 < qt2[1] or len2 < qt2[1]:
        return

    n1 = qt2[0]
    while n1 < qt2[1]:
        print("[", n1, "]:", v1[n1], sep, v2[n1])
        n1 = n1 + 1


def smeTimeDiff (tInit=None):
    import time

    if tInit == None:
        timeStart = time.time()
        clockStart = time.process_time()
        return {'time':timeStart, 'clock':clockStart}

    timeEnd = time.time()
    clockEnd = time.process_time()
    dTime = timeEnd - tInit['time']
    dClock = clockEnd - tInit['clock']
    return {'time':dTime, 'clock':dClock}
