# -*- coding: utf-8 -*-
"""
------------------------------------------------------------------
 Program: Mikro Funkstrecken - Swimming Pixel
 Karlsruhe University of Applied Science
 Authors: Jonas Felhauer, Matthias Essig
 Created on Wed Nov 11 16:43:34 2020
------------------------------------------------------------------
"""
import numpy as np

class ChirpSignal:
    def __init__(self, samplerate, start_freq, end_freq, start_amp, end_amp, chirp_duration, dtype=np.int16): #constructor
        self.mDtype = dtype
        self.mChirp = self.sin_chirp(chirp_duration, samplerate, start_freq, end_freq, start_amp, end_amp)        
        self.mSignal = self.stereo_chirp(self.mChirp)
        self.mReverseChirp = self.mChirp[::-1]
        
    def sin_chirp(self, duration, samplerate, start_freq, end_freq, start_amp, end_amp):
        #make sure that datatypes are float
        start_freq = float(start_freq)
        duration = float(duration)
        end_freq = float(end_freq)
        
        #calculate number of values related to samplerate and duration
        t = np.linspace(0.0, duration, int(samplerate * duration))
        
        #create sin signal with var freq but still const amp
        k = (end_freq - start_freq) / duration
        phase = 2 * np.pi * (start_freq * t + 0.5 * k * t**2)
        sin_chirp = np.sin(phase)
        
        #linear changing amp
        amp_lin = np.linspace(start_amp, end_amp, sin_chirp.size)
        
        #check for right datatype
        if self.mDtype is (np.int16 or np.int32):
            if self.mDtype is np.int16:
                sin_chirp[:] *= amp_lin[:]*20000
            else:
                sin_chirp[:] *= amp_lin[:]*1000000
        if self.mDtype is (np.float32 or np.float64):
            sin_chirp[:] *= amp_lin[:]
        
        #return chirp signal
        return sin_chirp 
      
    def stereo_chirp(self, signal : np.ndarray):
        #prepare array with right format and size
        stereo_signal = np.zeros((signal.size,2))
        
        #write signal to appropriate channel
        stereo_signal[:,1] = signal[:]
        stereo_signal[:,0] = signal[::-1]
        
        #return stereo signal
        return stereo_signal
                


