"""
Created on 11.11.21

@author: Joschka
"""
import numpy as np
import matplotlib.pyplot as plt
from src import coil_class as BC
from src import physical_constants as cs
import logging as log
import time

log.basicConfig(level=log.DEBUG, format='%(message)s')

def main():
    AHH_Coil = BC.BCoil(HH=-1, distance=69.313, radius=47, layers=8, windings=16,
                        wire_height=0.5, wire_width=0.5, insulation_thickness=0.068/2,
                        is_round=True, winding_scheme=2)

    x, z = BC.BCoil.make_axis(50, 5)

    I_current = 0.3804


    # print(BC.BCoil._BCoil__B_z_loop(I_current = I, r_loop = 1, z_loop = 1, r_pos = 0, z_pos = 0.1)
    #       - BC.BCoil._BCoil__B_z_loop(I_current = I, r_loop = 1, z_loop = -1, r_pos = 0, z_pos = 0.1))
    # print(BC.BCoil._BCoil__B_z_loop(I_current=I, r_loop=1, z_loop=1, r_pos=0, z_pos= -0.1)
    #       - BC.BCoil._BCoil__B_z_loop(I_current=I, r_loop=1, z_loop=-1, r_pos=0, z_pos=-0.1))


    step = 0.05
    xlim_mm = 30
    xlim = int(xlim_mm/step) + 1
    ylim_mm = 30
    ylim = int(ylim_mm/step) + 1
    zlim_mm = 20
    zlim = int(zlim_mm/step) + 1

    B_quarter = np.zeros((xlim, ylim, zlim, 2),dtype= np.float32)
    print(np.shape(B_quarter))
    #print(B_quarter)
    x = np.linspace(0,xlim_mm,xlim) * 1e-3
    y = np.linspace(0,ylim_mm,ylim) * 1e-3
    z = np.linspace(0,zlim_mm,zlim) * 1e-3

    calc_raster = AHH_Coil.full_raster(1)

    start = time.time()
    for wire in range(0,AHH_Coil.get_N()):
        print(f"time = {(time.time()-start)/60} min")
        print(f"wire = {wire} of {AHH_Coil.get_N()}")

        # extract position information out of raster
        z_pos = calc_raster[wire, 0, 0]
        r_pos = calc_raster[wire, 0, 1]
        for xx in range(0, xlim):
            for yy in range(0, ylim):

                r = np.sqrt(x[xx]**2 + y[yy]**2)

                # calculate z-component at x,y
                B_quarter[xx, yy, :, 1] += BC.BCoil._BCoil__B_z_loop(I_current, r_pos, z_pos, r, z) \
                                + BC.BCoil._BCoil__B_z_loop(AHH_Coil.HH * I_current, r_pos, -z_pos, r, z)

                if r == 0:
                    continue
                # calculate r-component at x, y
                B_quarter[xx, yy, :, 0] += BC.BCoil._BCoil__B_r_loop(I_current, r_pos, z_pos, r, z) \
                                   + BC.BCoil._BCoil__B_r_loop(AHH_Coil.HH * I_current, r_pos, -z_pos, r, z)

    np.save('output/final/B_quarter_1Gcm.npy', B_quarter)

    #B_tot = np.zeros(((2 * xlim) - 1, (2 * ylim) - 1, (2 * zlim)-1, 2))


    #AHH_Coil.B_quick_plot(5,50)
    #AHH_Coil.B_grad_quick_plot(5,50)


    # Bz, Bx = AHH_Coil.B_field(I_current, x, z)
    # B_tot_z, B_tot_x = AHH_Coil.B_field(I_current, x, z)















if __name__ == '__main__':
    main()