import numpy as np
import pandas as pd
import random, os, json

def valores_objetivo(archivo, material):
    carga = pd.read_excel(archivo, sheet_name='carga', engine='openpyxl').dropna()

    E = np.mean(carga.loc[carga['material'] == material, ['V1', 'V2']].values, axis=1)
    I = np.mean(carga.loc[carga['material'] == material, ['I1', 'I2']].values, axis=1)
    f = np.array(carga['f'][carga['material'] == material])
    
    return E, I, f


def generar_curva(offset, ruta):

    muVacio = 4 * np.pi * 1e-7

    with open("h_values/h_values.json", "r") as f : h = np.array(json.load(f))
    b = muVacio * h + offset

    with open(ruta, "w") as f:
        f.write('[PLACOND]\n')
        f.write('Type=Fixed_Solid\n')
        f.write('Solid Type=Plastic\n')
        f.write('Thermal Conductivity=0\n')
        f.write('Specific Heat=0\n')
        f.write('Density=1850\n')
        f.write('Notes=\n')
        f.write('ElectricalResistivity=0\n')
        f.write('TempCoefElectricalResistivity=0\n')
        f.write('PoissonsRatio=0\n')
        f.write('YoungsCoefficient=0\n')
        f.write('YieldStress=0\n')
        f.write(f'BValue[0]=0\n')
        f.write(f'HValue[0]=0\n')

        for i in np.arange(len(h)):
            f.write(f'BValue[{i+1}]={b[i]}\n')
            f.write(f'HValue[{i+1}]={h[i]}\n')



def logica_offset(offset, error, errorObjetivo):
    '''
    Coge el offset, error actual y lo analiza.

    devuelve flag y offset nuevo

    si se cumple la condicion devuelve 
    un True y None para offset

    '''

    limSup = 1 + errorObjetivo
    limInf = 1 - errorObjetivo

    delta = random.random() * 1e-6

    if error <= limSup and error >= limInf: return True, None
    
    if error > 1: offset = offset - delta
    elif error < 1: offset = offset + delta

    return False, offset



if __name__ == '__main__':
    '''
    Esto solo se activa si se lanza este script en concreto
    no si se invocan las funciones desde otro script.

    Contiene ejemplos de como funciona el codigo para ver
    como funciona todo

    '''

    directorio = ''
    nombre = "PLACond.mdb"

    ruta = f'{directorio}{nombre}'
    offset = 0

    generar_curva(offset,ruta)


    # B = 1e-2
    # BObjetivo = 2e-2

    # errorObjetivo = 0.01

    # flag = False

    # while flag == False:
    #     os.system('cls')

    #     B = B + offset

    #     error = B/BObjetivo

    #     print(B)
    #     print(error)

    #     flag, offset = logica_offset(offset, error, errorObjetivo)