#Løser difflikningen for systemet numerisk
from tools.global_constants import *
from tools.ping_pong_constants import *


def alfa_laminer_func(theta,w): #difflikning løst mhp alfa ved laminær strømning
    return (-g*np.sin(theta)-((k*R*w)/m))/(R*(1+c))

def alfa_turbulent_func(theta,w): #difflikning løst mhp. alfa ved turbulens
    if w:
        return (-g * np.sin(theta) - (((0.5*roh*A*Cd * (R*w)**2) / m)*(w/abs(w)))) / (R * (1 + c))
    return -g * np.sin(theta)/ (R * (1 + c))

def next_point(theta,w,alfa):
    theta_2 = theta + w * dt + alfa* (dt**2)    #s = v_0 * t + a*t^2
    w_2 = w + alfa * dt

    if check_turbulens(w):
        alfa_2 = alfa_turbulent_func(theta_2,w_2)
        return theta_2, w_2, alfa_2

    else:
        alfa_2 = alfa_laminer_func(theta_2, w_2)
        return theta_2, w_2, alfa_2

def laminer_next_point(theta,w,alfa): #ett euler-skritt ved laminær strømning
    theta_2 = theta + w*dt
    w_2 = w + alfa*dt
    alfa_2 = alfa_laminer_func(theta_2,w_2)

    return theta_2,w_2,alfa_2

def turbulent_next_point(theta,w,alfa): #ett euler-skritt ved turbulent strøming
    theta_2 = theta + w * dt
    w_2 = w + alfa * dt
    alfa_2 = alfa_turbulent_func(theta_2, w_2)

    return theta_2, w_2, alfa_2

def check_end(theta,w): #stanser numerisk beregning
    if (abs(theta)+abs(w)) < slutt:
        return True
    return False

def check_end_tid(tid_list): #stanser numerisk beregning
    if tid_list[-1] > slutt_tid:
        return True
    return False

def check_turbulens(w): #skjekker om hastigheten er høy nok til turbulens
    if abs(w) > w_turbulens:
        return True
    return False

def gen_list(theta_0,w_0, turb = 0): #implementasjon av euler, returnerer numerisk løsning av theta,w, alfa, med tilhørende tid_list
    global w_turbulens
    if turb != 0: #turb er hastigheten hvor turbulens slår inn, dersom man ikke vil bruke den globale
        w_turbulens = turb

    #initialbetingelse for alfa
    alfa_0 = alfa_laminer_func(theta_0, w_0)

    theta,w,alfa = theta_0,w_0,alfa_0

    theta_list = [theta]
    w_list = [w]
    alfa_list = [alfa]
    tid_list = [0]

    for i in range(4):

        theta,w,alfa = next_point(theta,w,alfa)

        theta_list.append(theta)
        w_list.append(w)
        alfa_list.append(alfa)
        tid_list.append(tid_list[-1] + dt)

    while not check_end_tid(tid_list):
        theta,w,alfa = next_point(theta,w,alfa)

        theta_list.append(theta)
        w_list.append(w)
        alfa_list.append(alfa)
        tid_list.append(tid_list[-1]+dt)

    return theta_list,w_list,alfa_list,tid_list