import numpy as np
import scipy.constants as cst
from numba import njit

def init_const(dx, h_size, l_size, b_size):

    c_spec = 1006 #Specific heat capacity air 
    D = 1.6 * 10**-5 #Diffusion coefficient of CO2 in air
    alpha =  2.1 * 10**-5 #Thermal diffusivity of air
    R_s = 287.1 #Specific gas constant of air
    nu =  1.51 * 10**-5 #Kinematic viscosity of air (20°C)
    g = cst.g #Gravitational acceleration
    V = dx**3 * 2*((h_size+1)*(l_size+1)+(l_size+1)*(b_size+1)+(b_size+1)*(h_size+1)) #Volume of Human surface in Simulation 

    return c_spec, D, alpha, R_s, nu, V, g



def init_temp(h, l, b, h_source, l_source, b_source, dx, D_B):
    # Initial temperature field, body box and nostril position

    T_start = 273.15 + 24.28    # mean initial air temperature (SI Sec. VI.B)
    T_window = 273.15 + 25.22   # window surface temperature (SI Table III)

    # Measured wall temperatures (SI Table III): 23.86, 23.60, 24.01, 23.80, 23.92, 23.99 °C
    T_left, T_right, T_front, T_back, T_up, T_down = 273.15 + 23.86, 273.15 + 23.60, 273.15 + 24.01, 273.15 + 23.80, 273.15 + 23.92, 273.15 + 23.99

    delta_T = 0.51 # initial linear temperature gradient over the room height: 0.3 K * 2.55 m / 1.5 m (SI Sec. VI.B)
    T_grad = np.linspace(0, delta_T, h).reshape((h, 1, 1))
    T = T_start - delta_T / 2 + T_grad * np.ones((h, l, b)) 

    # Wall temperatures (floor, ceiling, front, back, left, right), window on the back wall
    T[0,:,:], T[h-1,:,:], T[:,0,:], T[:,l-1,:], T[:,:,0], T[:,:,b-1] = T_down, T_up, T_front, T_back, T_left, T_right
    T[int(round(0.20/dx,0)):int(round(2/dx,0)),-1,int(round(1.3/dx,0)):int(round(2.10/dx,0))] = T_window

    # Body of the seated person: box of 0.8 m x 0.25 m x 0.4 m (height x length x depth)
    h_size, l_size, b_size = round(0.8/dx,0), round(0.25/dx,0), round(0.4/dx,0)
    body_arr = np.array([int(h_source-h_size+1), int(h_source+1), int(l_source-l_size-1), int(l_source-1), int(b_source-0.5*b_size), int(b_source+0.5*b_size)])
 
    T[body_arr[0]:body_arr[1]+1,body_arr[2]:body_arr[3]+1,body_arr[4]:body_arr[5]+1] = 0 
    
    # Nostril: square opening of side D_B on the front face of the body
    length = int(round(D_B / dx))
    if  length == 0:
        print("ATTENTION! The nostril size is much smaller than the dx. This will cause errors in the simulation.")

    nostril = np.array([h_source+1-length, h_source, l_source-1, b_source+1-(length+1)//2, b_source+length//2], dtype=np.int16) 

    print("The target nostril size is "+str(D_B)+"m.")
    print("The nostril has a x size of "+str((nostril[1]-nostril[0]+1)*dx)+"m and z size of "+str((nostril[4]-nostril[3]+1)*dx)+"m.")

    return T, body_arr, h_size, l_size, b_size, T_start, nostril


def init_grid(simulationTime, dx, dt):

    steps = int(round(simulationTime/dt,0)) #number of time steps
    h, l, b = int(round(2.55/dx,0)+1), int(round(5.75/dx,0)+1), int(round(2.85/dx,0)+1) # 2,55m x 5,75m x 2,85m
    h_source, l_source, b_source = int(round(1.1/dx,0)), int(round(1/dx,0)), int(round((2.85/2)/dx,0)) # 1,1m x 1m x 1,425m 

    h_det, l_det, b_det = int(round(0.30/dx,0)), int(round(3.75/dx,0)), int(round((2.85/2)/dx,0)) # 0,30m x 3,75m x 1,425m 
 
    source = np.array([h_source, l_source, b_source], dtype=np.int8)
    assert source.min() >= -128 and source.max() <= 127 # guards against int8 overflow

    detector = np.array([h_det, l_det, b_det])

    return steps, h, l, b, source, h_source, l_source, b_source, detector



def init_rho_c_v(rho_start, h, l, b, body_arr, dx, H, T, T_start):

    # Initial density: adiabatic barometric height formula, see SI Eq. (38), Section VII.B
    gamma = 1.4
    rho = np.empty((h, l, b)) 

    for x in range(h):
        factor = 1.0 - ((gamma - 1.0) / gamma) * (x * dx / H)
        rho[x, :, :] = factor ** (1.0 / (gamma - 1.0)) * (1 - (T[x, int(l // 2), int(b // 2 )] / T_start - 1))

    mid_x, mid_y, mid_z = int(h/2), int(l/2), int(b/2)
    rho *= rho_start / rho[mid_x, mid_y, mid_z]

    rho[0::h-1,:,:], rho[:,0::l-1,:], rho[:,:,0::b-1] = 0, 0, 0
    rho[body_arr[0]:body_arr[1]+1,body_arr[2]:body_arr[3]+1,body_arr[4]:body_arr[5]+1] = 0

    c = np.ones((h, l, b)) * 455
    c[0::h-1,:,:], c[:,0::l-1,:], c[:,:,0::b-1] = 0, 0, 0 
    c[body_arr[0]:body_arr[1]+1,body_arr[2]:body_arr[3]+1,body_arr[4]:body_arr[5]+1] = 0

    
    vx, vy, vz = np.zeros((h-1, l, b)), np.zeros((h, l-1, b)), np.zeros((h, l, b-1))

    return rho, c, vx, vy, vz

@njit
def body(x_size, y_size, z_size, body, nostril):

    # Cell-type map for scalar fields (c, rho, T), one value per grid point:
    #   -1    : inside the body or on the outer domain boundary (not updated)
    #    0    : ordinary air cell
    #  1-3   : cell next to a wall; the value counts how many walls it touches (edge/corner)
    #    4    : air cell on the surface of the body (heat source)
    Is_body_long = np.zeros((x_size, y_size, z_size), dtype=np.int8)

    # No-slip masks for the velocity components on the staggered grid
    # (1 = velocity is not updated, i.e. set to zero; 0 = normal update)
    Is_body_x = np.zeros((x_size, y_size, z_size), dtype=np.uint8)  # for v_x
    Is_body_y = np.zeros((x_size, y_size, z_size), dtype=np.uint8)  # for v_y
    Is_body_z = np.zeros((x_size, y_size, z_size), dtype=np.uint8)  # for v_z

    for x in range(1, x_size-1):
        for y in range(1, y_size-1):
            for z in range(1, z_size-1):

                Is_body = int((x >= body[0])) + int((x <= body[1])) + int((y >= body[2])) + int((y <= body[3])) + int((z >= body[4])) + int((z <= body[5]))

                if Is_body == 6:

                    Is_body_long[x,y,z] = -1 #grid point is within body

                Is_border = (x == 0) or (y == 0) or (z == 0) or (x == x_size-1) or (y == y_size-1) or (z == z_size-1)

                if Is_border == True:

                    Is_body_long[x,y,z] = -1 #grid point is on the border

                Is_edge = ((x == 1) + (y == 1) + (z == 1) + (x == x_size-2) + (y == y_size-2) + (z == z_size-2))

                if Is_edge != 0:

                    Is_body_long[x,y,z] = Is_edge #grid point is on the edge

                body_x = int(((x == body[0]-1) or (x == body[1]+1)) and (y >= body[2]) and (y <= body[3]) and (z >= body[4]) and (z <= body[5]))
                body_y = int(((y == body[2]-1) or (y == body[3]+1)) and (x >= body[0]) and (x <= body[1]) and (z >= body[4]) and (z <= body[5]))
                body_z = int(((z == body[4]-1) or (z == body[5]+1)) and (x >= body[0]) and (x <= body[1]) and (y >= body[2]) and (y <= body[3]))
                body_num = body_x + body_y + body_z  

                if body_num != 0:

                    Is_body_long[x,y,z] = 4 #grid point is on the surface of the body 

                # No-slip mask around the body (two-voxel layer, see SI Section IV.B)
                # ---------------------------------------------------------------------------
                # Model II (no breathing): two-voxel layer on all faces of the body.
                # (Model I has no flow field and does not use this mask.)
                #Is_body_x[x, y, z] = (x >= body[0]-2) and (x <= body[1]+1) and (y >= body[2]-2) and (y <= body[3]+2) and (z >= body[4]-2) and (z <= body[5]+2) or (x == x_size-2)
                #Is_body_y[x, y, z] = (x >= body[0]-2) and (x <= body[1]+2) and (y >= body[2]-2) and (y <= body[3]+1) and (z >= body[4]-2) and (z <= body[5]+2) or (y == y_size-2)
                #Is_body_z[x, y, z] = (x >= body[0]-2) and (x <= body[1]+2) and (y >= body[2]-2) and (y <= body[3]+2) and (z >= body[4]-2) and (z <= body[5]+1) or (z == z_size-2)

                # Model III (with breathing, see SI Section IV.B): on the nostril face (+y) the layer is reduced to
                # one voxel, so the exhaled air does not pass through a no-slip layer.
                Is_body_x[x, y, z] = (x >= body[0]-2) and (x <= body[1]+1) and (y >= body[2]-2) and (y <= body[3]+1) and (z >= body[4]-2) and (z <= body[5]+2) or (x == x_size-2)
                Is_body_y[x, y, z] = (x >= body[0]-2) and (x <= body[1]+2) and (y >= body[2]-2) and (y <= body[3]) and (z >= body[4]-2) and (z <= body[5]+2) or (y == y_size-2)
                Is_body_z[x, y, z] = (x >= body[0]-2) and (x <= body[1]+2) and (y >= body[2]-2) and (y <= body[3]+1) and (z >= body[4]-2) and (z <= body[5]+1) or (z == z_size-2)

    return Is_body_long, Is_body_x, Is_body_y, Is_body_z
