import torch
import torchaudio
import torch.utils.data
from torch.utils.data import Dataset
from scipy.io.wavfile import read
from librosa.filters import mel as librosa_mel_fn

mel_basis = {}
hann_window = {}

def load_wav(full_path):
    sampling_rate, data = read(full_path)
    return data, sampling_rate

def dynamic_range_compression_torch(x, C=1, clip_val=1e-5):
    return torch.log(torch.clamp(x, min=clip_val) * C)

def dynamic_range_decompression_torch(x, C=1):
    return torch.exp(x) / C

def spectral_normalize_torch(magnitudes):
    output = dynamic_range_compression_torch(magnitudes)
    return output

def spectral_de_normalize_torch(magnitudes):
    output = dynamic_range_decompression_torch(magnitudes)
    return output

mel_basis = {}
hann_window = {}

def mel_spectrogram(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fmin, fmax, center=True):
    if torch.min(y) < -1.:
        print('min value is ', torch.min(y))
    if torch.max(y) > 1.:
        print('max value is ', torch.max(y))

    global mel_basis, hann_window
    if fmax not in mel_basis:
        mel = librosa_mel_fn(sampling_rate, n_fft, num_mels, fmin, fmax)
        mel_basis[str(fmax)+'_'+str(y.device)] = torch.from_numpy(mel).float().to(y.device)
        hann_window[str(y.device)] = torch.hann_window(win_size).to(y.device)


    # reflectionPad1d = torch.nn.ReflectionPad1d((int((n_fft-hop_size)/2), int((n_fft-hop_size)/2)))
    # y = reflectionPad1d(y.unsqueeze(0).unsqueeze(0))
    y = torch.nn.functional.pad(y.unsqueeze(0).unsqueeze(0), (int((n_fft - hop_size) / 2), int((n_fft - hop_size) / 2)),
                                mode='reflect')
    y = y.squeeze(0).squeeze(0)

    spec = torch.stft(y, n_fft, hop_length=hop_size, win_length=win_size, window=hann_window[str(y.device)],
                      center=center, pad_mode='reflect', normalized=False, onesided=True)

    spec = torch.sqrt(spec.pow(2).sum(-1)+(1e-9))

    spec = torch.matmul(mel_basis[str(fmax)+'_'+str(y.device)], spec)
    spec = spectral_normalize_torch(spec)

    return spec

class LJSpeech(Dataset):
    def __init__(self, X, y, config, train=True):
        super().__init__()
        self.names = X
        self.labels = y
        self.train = train
        self.config = config

    def __len__(self):
        return len(self.names)

    def __getitem__(self, idx):
        img = torch.zeros(self.config.melspec_n_mels, self.config.img_pad_len)
        audio, sr = torchaudio.load(self.config.dataset_path + 'wavs/' + self.names[idx] + '.wav')
        mel = mel_spectrogram(audio, self.config.melspec_n_fft, self.config.melspec_n_mels,
                              self.config.melspec_sample_rate, self.config.melspec_hop_length,
                              self.config.melspec_win_size, self.config.melspec_f_min,
                              self.config.melspec_fmax_loss, center=True).squeeze(0)
        img[:, :mel.size(1)] = mel

        target = torch.tensor(
            self.labels[idx] + [self.config.txt_pad_idx] * (self.config.txt_pad_len - len(self.labels[idx])))
        target_len = torch.tensor(len(self.labels[idx]) + 1)
        padded_len = torch.tensor(self.config.img_pad_len)

        return img, target, target_len, padded_len