from PyPFD import PyPFDMarkovTransition

def matrix_mul(A,B):
    resultado = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]

# Multiplicação
    for i in range(len(A)):
        for j in range(len(B[0])):
            for k in range(len(B)):
                resultado[i][j] += A[i][k] * B[k][j]


    return resultado

def markov_cal_Ntest(transitionM,safeV,testsM,testV):

    rM = [[0 for _ in range(len(transitionM))]]
    rM[0][0] = 1
    pfd = 0 
    ntest = len(testV)

    maxT = 0
    for tst in testV:

        if tst > maxT: 
            maxT = tst

    safeM = []

    if len(safeV) > 1:
        safeM.append(safeV)
    else:
        safeM = safeV

    for i in range(maxT):
       rM = matrix_mul(rM,transitionM)

       for k in range(ntest):
          if i % testV[k] == 0:
           rM = matrix_mul(rM,testsM[k])
   
       for j in range(len(rM[0])):
           if safeM[0][j] == 0:
             pfd+=rM[0][j]

    pfd = pfd/maxT

    return {"stateVector": rM, "pfdavg":pfd}

def markov_cal_Ntest_plot(transitionM,safeV,testsM,testV,n_pt):

    rM = [[0 for _ in range(len(transitionM))]]
    rM[0][0] = 1
    pfd = 0 
    ntest = len(testV)

    maxT = 0
    for tst in testV:
        if tst > maxT: 
            maxT = tst


    interval = int(maxT/(n_pt-1))   

    tempo = []
    returnM = rM
    tempo.append(0)

    safeM = []

    if len(safeV) > 1:
        safeM.append(safeV)
    else:
        safeM = safeV

    for i in range(maxT):
       rM = matrix_mul(rM,transitionM)

       for k in range(ntest):
          if i % testV[k] == 0:
           rM = matrix_mul(rM,testsM[k])
   
       for j in range(len(rM[0])):
           if safeM[0][j] == 0:
             pfd+=rM[0][j]

       if i % interval == 0:
            returnM = returnM + rM
            tempo.append(i)  
 

    pfd = pfd/maxT

    return {"stateMatrix": returnM, "pfdavg":pfd, "tempo": tempo}


