import pandas as pd
import numpy as np
from scipy.interpolate import LinearNDInterpolator


# Positive Thrust (F_WASP) -> Forward
# Negative Thrust (F_WASP) -> Stern
# Positive Side Force (F_SIDE) -> Starboard
# Negative Side Force (F_SIDE) -> Port



class rotorSail:
    def __init__(self, model_data_file, nb_rotors=1):
        self.model_data_file = model_data_file
        self.nb_rotors = nb_rotors

        self.data = pd.read_csv(self.model_data_file, sep=';', header=0)
        # AWA [deg]	AWS [m/s]	SR	Thrust [N]	SideF [N]	P_spin [W]	z_ac [m]

        alpha = np.array(self.data['AWA [deg]'], dtype=float)
        v_wind = np.array(self.data['AWS [m/s]'], dtype=float)
        F = np.array(self.data['T [N]'], dtype=float)
        side_force = np.array(self.data['SideF [N]'], dtype=float)
        sr = np.array(self.data['SR'], dtype=float)

        self.sr_max = np.max(sr)

        P_spin = np.array(self.data['P_spin [W]'], dtype=float)

        self.rotor_spin_power_interp = LinearNDInterpolator(list(zip(alpha, v_wind, sr)), P_spin)
        # Force interpolator, F = f(alpha, speed, SR)
        self.force_interp = LinearNDInterpolator(list(zip(alpha, v_wind, sr)), F)
        # Side force interpolator SF = f(alpha, speed, SR)
        self.side_force_interp = LinearNDInterpolator(list(zip(alpha, v_wind, sr)), side_force)

    def assist(self, ws, wa, sr): # apparent wind speed, apparent wind angle, spin ratio
        if sr > self.sr_max:
            print('SR out of boundaries.')
            sr = self.sr_max
        F_WASP = float( self.force_interp(wa, ws, sr)) * self.nb_rotors
        P_SPIN = float(self.rotor_spin_power_interp(wa, ws, sr)) * self.nb_rotors * 1e-3 # kW
        F_SIDE = float(self.side_force_interp(wa, ws, sr)) * self.nb_rotors

        return {'F':F_WASP, 'P_SPIN': P_SPIN,'F_SIDE':F_SIDE} # [N], [kW], [N]





####Example :
#file = 'data/RotorSail_D-5_De-6_height-35.csv'
#nb_rotors = 1
#rotor = rotorSail(file,nb_rotors)
#ws = 8 # Apparent Wind Speed, [m.s-1]
#wa = 50 # Apparent Wind Angle, [deg]
#sr = 2 # Spin Ratio
#print(rotor.assist(ws, ws, sr))
