import matplotlib.pyplot as plt
import numlos
from tools import file_handling as dtr, edit_list as ed, vinkelfart as vf
from tools.ping_pong_constants import *
from tools.global_constants import *

def plot_txy(plot_name='', data_name='',t_list='',x_list='',y_list=''): #plotter x og y mot t

    t_list, x_list, y_list = dtr.file_to_txy(data_name)

    plt.figure()
    plt.plot(t_list,x_list, color = 'b', label = 'x')
    plt.plot(t_list, y_list, color = 'r', label = 'y')

    plt.legend(loc='upper left')
    plt.xlabel('t')

    vis = input('vis plot? (j/n)')
    if vis == 'j':
        plt.show()

    plt.savefig('plots/'+plot_name)

def plot_tTheta(plot_name='', data_name='',t_list='',theta_list=''):    #plotter theta mot t
    if data_name:
        t_list, theta_list = dtr.file_to_tTheta(data_name)

    plt.figure()
    plt.plot(t_list,theta_list)

    plt.xlabel('t')
    plt.ylabel('theta / [pi]')

    vis = input('vis plot? (j/n)')
    if vis == 'j':
        plt.show()

    else:
        plt.savefig('plots/'+plot_name)

def plot_bane(plot_name='', data_name='', x_list='', y_list = ''): #plotter x mot y
    if data_name:
        x_list, y_list = dtr.file_to_xy(data_name)

    plt.figure()
    plt.plot(x_list, y_list)

    plt.xlabel('x-posisjon')
    plt.ylabel('y-posisjon')

    vis_sirkel = input('vis sentrum i sirkel? (j/n)')
    if vis_sirkel == 'j':

        R = ed.find_radius(x_list, y_list)

        s_x = np.linspace(-R,R,1000)
        s_y = [-(np.sqrt(R**2 - x**2)) for x in s_x]
        plt.plot(s_x,s_y)
        plt.plot([0],[0],marker='.')


    vis = input('vis plot? (j/n)')
    if vis == 'j':
        plt.show()

def plot_twa(theta_list,w_list,alfa_list): #plotter numerisk theta, w, alfa som funksjon av tid

    t_list = np.linspace(0,dt*len(theta_list),len(theta_list))

    plt.figure()
    plt.plot(t_list,theta_list,color='r', label='theta')
    plt.plot(t_list,w_list, color='b', label='w')
    plt.plot(t_list,alfa_list, color='g', label='alfa')

    plt.plot([0,t_list[-1]],[0,0], color='B') #støttelinjer

    plt.legend()
    plt.title('k = '+str(k) + ' Cd = ' + str(Cd) + ' w_turb = '+ str(w_turbulens))

    plt.xlim(0,10)

    plt.show()
    plt.close()

def plot_svingninger_mot_num(filename): #plotter en og en eksperimentell svingning mot tilsvarende numerisk svingning
    t, theta = dtr.file_to_tTheta(filename)

    theta, t = ed.svingningsfinner(theta, t)

    for i in range(len(theta)):
        t[i] = ed.adjust_t0(t[i])
        plt.plot(t[i], theta[i])

def plot_luftmotstand_mot_vinkelfart(save=False):   #plotter luftmotstand mot vinkelfart
    t, theta = dtr.file_to_tTheta('gjennomsnitt.txt')

    theta_sving, t_sving = ed.svingningsfinner(theta, t)
    t_sving = [ed.adjust_t0(t_list) for t_list in t_sving]
    for i in range(len(theta_sving)):
        if len(t_sving[i]) > 15:

            luft_list = vf.luftmotstand(t_sving[i], theta_sving[i])
            fart_list = vf.vinkelfart(t_sving[i], theta_sving[i])

            try:        #en av listene er har 3 elementer pga. en spesialtilfelle i svingningsfinner
                plt.plot(fart_list[2:-50], luft_list[2:-50], color='r')
            except ValueError:
                print(i, ' : ', t_sving[i])

            plt.xlabel('Vinkelhastighet [1/s]')
            plt.ylabel('Luftmotstand [N]')

            plt.xlim(-0.45, 0.45)
            plt.ylim(-0.0035, 0.0035)

            plt.savefig('plots/luftmotstand_vinkelfart_svingning_' + str(i))
            plt.show()

def plot_normalkraft_theta():   #plotter normalkraft mot theta
    t, theta = dtr.file_to_tTheta('gjennomsnitt.txt')
    theta, w, alfa, tid = numlos.gen_list(theta[0], 0)
    w = np.array(w)
    theta = np.array(theta)
    alfa = np.array(alfa)

    v = R * w  # hastighet fra vinkelhastighet og radius
    G_n = - m * g * np.cos(theta)  # G normalt på banen
    S = m * (v ** 2) / R  # sentripetalkraften

    N = S - G_n  # S = N + G_n

    f = c * m * R * alfa

    plt.plot(theta, N)
    plt.xlabel('Vinkelutslag')
    plt.ylabel('Normalkraft [N]')
    plt.savefig('plots/normalkraft_theta')

def plot_theta_numerikk(): #plotter vinkelutslag fra eksperimentell og numerisk data mot tid i samme plot for en svingning av gangen
    t, theta = dtr.file_to_tTheta('gjennomsnitt.txt')

    theta_sving, t_sving = ed.svingningsfinner(theta, t)
    t_sving = [ed.adjust_t0(t_list) for t_list in t_sving]

    farger = ['r', 'g', 'b', 'y', 'c', 'm'] * 2

    for i in range(len(theta_sving)):
        n_theta, n_w, n_a, n_tid = numlos.gen_list(theta_sving[i][0], 0)
        plt.plot(n_tid, n_theta, label='Numerikk')
        plt.plot(t_sving[i], theta_sving[i], label='Eksperimentell')

        plt.xlim(0, 2)
        plt.ylim(-0.2, 0.2)

        plt.xlabel('Tid [s]')
        plt.ylabel('Vinkelutslag (radianer)')

        plt.legend(loc='lower left')
        plt.savefig('plots/theta_mot_numerikk_' + str(i))
        plt.show()

    plt.plot(t, theta, label='Data')
    plt.plot(n_tid, n_theta, label='Numerikk')
    plt.legend()
    plt.show()

def plot_eksperimentell_mot_lam_turb(): #plotter eksperimentelt vinkelutslag mot laminær og turbulent modell, for en svingning av gangen
    t, theta = dtr.file_to_tTheta('gjennomsnitt.txt')

    theta_sving, t_sving = ed.svingningsfinner(theta, t)
    t_sving = [ed.adjust_t0(t_list) for t_list in t_sving]

    for i in range(len(theta_sving)):
        n_turb_theta, n_turb_w, n_turb_a, n_turb_tid = numlos.gen_list(theta_sving[i][0], 0, turb=0.1)
        plt.plot(n_turb_tid, n_turb_theta, label='Turbulent numerikk')

        n_lam_theta, n_lam_w, n_lam_a, n_lam_tid = numlos.gen_list(theta_sving[i][0], 0, turb=1)
        plt.plot(n_lam_tid, n_lam_theta, label='Laminær numerikk')

        plt.plot(t_sving[i], theta_sving[i], label='Eksperimentell')

        plt.xlim(0, 2)
        plt.ylim(-0.2, 0.2)

        plt.xlabel('Tid [s]')
        plt.ylabel('Vinkelutslag (radianer)')

        plt.legend(loc='lower left')
        plt.savefig('plots/theta_mot_lam_turb_' + str(i))
        plt.show()

def normal_friksjon(): #plotter normalkraft og friksjonskraft som funksjon av vinkelutslag (bruker numerisk data)
    t, theta = dtr.file_to_tTheta('gjennomsnitt.txt')
    theta, w, alfa, tid = numlos.gen_list(theta[0], 0)
    w = np.array(w)
    theta = np.array(theta)
    alfa = np.array(alfa)

    v = R * w  # hastighet fra vinkelhastighet og radius
    G_n = - m * g * np.cos(theta)  # G normalt på banen
    S = m * (v ** 2) / R  # sentripetalkraften

    N = S - G_n  # S = N + G_n

    f = c * m * R * alfa

    plt.plot(theta, f)
    plt.xlabel('Vinkelutslag')
    plt.ylabel('Friksjonskraft [N]')
    plt.savefig('plots/friksjon_theta')

    plt.show()

def vinkelfart_mot_numerikk(): #plotter eksperimentell vinkelfart mot numerisk vinkelfart
    t,theta = dtr.file_to_tTheta('gjennomsnitt.txt')
    theta_sving,t_sving = ed.svingningsfinner(theta,t)

    for i in range(len(t_sving)):
        print(i)
        t_sving[i] = ed.adjust_t0(t_sving[i])
        fart = (vf.vinkelfart(t_sving[i],theta_sving[i]))
        #fart = [fart[i] - fart[1] for i in range(len(fart))]

        n_theta,n_turb_w,n_a,n_t = numlos.gen_list(theta_sving[i][0],fart[0],turb=0.001)
        n_theta, n_lam_w, n_a, n_t = numlos.gen_list(theta_sving[i][0], fart[0], turb=1)

        n_t = n_t[70:]
        n_t = ed.adjust_t0(n_t)

        plt.plot(n_t,n_turb_w[70:], label='Turbulent')
        plt.plot(n_t,n_lam_w[70:], label = 'Laminær')
        plt.plot(t_sving[i][1:-20], fart[1:-20], label='Data')

        plt.xlabel('Tid [s]')
        plt.ylabel('Vinkelfart [1/s]')

        plt.xlim(0,2)
        plt.legend(loc='best')

        plt.savefig('plots/fart_mot_numerikk_'+str(i))
        plt.show()

def usikker_w(glatt=15): #plotter eksperimentell vinkelfart med usikkerhet, hvor steglengde i utregningen er 'glatt'
    t, x, y = dtr.file_to_txy('gjennomsnitt.txt')
    
    theta, del_theta = ed.theta_usikker(x,y)

    w, delta_theta, delta_t = vf.vinkelfart(t, theta, usikker=True, glatt=glatt)
    w, delta_theta, delta_t = [np.array(x) for x in [w, delta_theta, delta_t]]

    del_w = abs(w) * np.sqrt((2 * del_theta / delta_theta) ** 2 + (2 * del_t / delta_t) ** 2)

    plt.plot(t[:-20], w[:-20])

    upper = w + del_w
    lower = w - del_w

    plt.fill_between(t[:-20], lower[:-20], upper[:-20], color='b', alpha=0.2)

    plt.xlim(0, 5)
    plt.xlabel('Tid [s]')
    plt.ylabel('Vinkelfart [1/s]')
    plt.savefig('plots/vinkelfart_usikkerhet_glatt' + str(glatt))
    plt.show()

def usikker_alfa(glatt=30): #plotter vinkelakselerasjon med usikkerhet, hvor steglengde i utregningen er 'glatt'
    t, x, y = dtr.file_to_txy('gjennomsnitt.txt')
    theta, del_theta = ed.theta_usikker(x,y)

    alfa, delta_w, delta_t = [np.array(x) for x in vf.vinkelakselerasjon(t, theta, usikker=True, glatt=glatt)]

    w, delta_theta, delta_t = vf.vinkelfart(t, theta, usikker=True, glatt=glatt)
    w, delta_theta, delta_t = [np.array(x) for x in [w, delta_theta, delta_t]]

    del_w = abs(w) * np.sqrt((2 * del_theta / delta_theta) ** 2 + (2 * del_t / delta_t) ** 2)
    del_alfa = abs(alfa) * np.sqrt((2 * del_w / delta_w) ** 2 + (2 * del_t / delta_t) ** 2)

    plt.plot(t[:-20], alfa[:-20])

    upper = w + del_alfa
    lower = w - del_alfa

    plt.fill_between(t[:-20], lower[:-20], upper[:-20], color='b', alpha=0.2)

    plt.ylim(-3, 3)
    plt.xlim(0.1, 2)

    plt.ylabel('Vinkelakselerasjon [1/s^2]')
    plt.xlabel('Tid [s]')

    plt.savefig('plots/vinkelaks_usikkerhet_glatt30')
    plt.show()

def luft_usikker(): #plotter eksperimentell luftmotstand mot tid med usikkerhet
    t,x,y = dtr.file_to_txy('gjennomsnitt.txt')
    luft,del_luft = ed.luftmotstand(t,x,y)
    upper = np.array(luft) + np.array(del_luft)
    lower = np.array(luft) - np.array(del_luft)

    plt.plot(t,luft)
    plt.fill_between(luft,upper,lower)
    plt.show()

def usikker_theta(): #plotter eksperimentelt vinkelutslag med usikkerhet
    t, x, y = dtr.file_to_txy('gjennomsnitt.txt')

    theta, del_theta = [np.array(x) for x in ed.u_theta(x, y)]
    theta, t, del_theta = [x[5] for x in ed.svingningsfinner(theta, t, del_theta)]

    upper = theta + del_theta
    lower = theta - del_theta

    plt.plot(t, theta, color='b')
    plt.fill_between(t, upper, lower, alpha=0.2)
    plt.xlabel('Tid [s]')
    plt.ylabel('Vinkelutslag (radianer)')
    plt.xlim(12.3, 14.4)
    plt.ylim(-0.08, 0.065)
    plt.savefig('plots/theta_usikker')

    plt.show()

def usikker_luftmotstand(): #plotter eksperimentell luftmotstand mot tid med usikkerhet
    t, x, y = dtr.file_to_txy('gjennomsnitt.txt')
    luft, del_luft, w = ed.usikker_luftmotstand(t, x, y)

    upper = np.array(luft) + np.array(del_luft)
    lower = np.array(luft) - np.array(del_luft)

    plt.plot(w[:-50], luft[:-50], color='r')
    plt.fill_between(w[50:-50], upper[50:-50], lower[50:-50], color='b', alpha=0.2)
    plt.ylim(-0.002, 0.002)
    plt.xlim(0, 1.75)

    plt.xlabel('Vinkelfart [1/s]')
    plt.ylabel('Luftmotstand [N]')

    plt.savefig('plots/luftmotstand_vinkelfart_svingning_uten5')

    plt.show()