import random


def _split_dataset(X,Y, train_perc = 0.7, dev_perc = 0.15, m_clip=5000, do_shuffle=False, n_samples_per_training_split = None):
    """Splits a dataset into training development and test sets.
    
    Optionally shuffle the dataset before splitting. The splits are sized
    according to the given percentages, but dev and test sets sizes are clipped
    to m_clip samples each.
    Samples are taken in the following order: dev, test, train. This information
    can be useful during error analysis to match the audio samples to the
    samples in each split.
    The training set can be further split in chunks of a predefined size.
    
    Args:
        X (numpy.ndarray): The X matrix.
        Y (numpy.ndarray): The Y matrix.
        train_perc (float): The percentage of data to be destined to training set [0-1].
        dev_perc (float): The percentage of data to be destined to dev set [0-1].
        m_clip (int): The maximum number of samples of dev and test sets.
        do_shuffle (boolean): Wheter to shuffle the dataset before splitting.
        n_samples_per_training_split (int): The number of samples per each
            chunk of training set or None not to split training set in chunks.
    
    Returns:
        list: X splits
        list: Y splits
        int: number of training samples
    """
    
    #SHUFFLING
    m = X.shape[0]
    
    if do_shuffle is True:
        shuffled = list(range(m))
        random.shuffle(shuffled)
        X_shuf = X[shuffled,:]
        Y_shuf = Y[shuffled,:]
    else:
        X_shuf = X
        Y_shuf = Y
        
    #SPLITTING'
    train_perc = 0.7
    dev_perc = 0.15
    
    test_perc = 1.0-train_perc-dev_perc
    dev_cum = int(min(dev_perc*m,10000))
    test_cum = int(dev_cum + min(test_perc*m, m_clip))
    
    X_dev = X_shuf[0:dev_cum]
    Y_dev = Y_shuf[0:dev_cum]
    X_test = X_shuf[dev_cum:test_cum]
    Y_test = Y_shuf[dev_cum:test_cum]
    X_train = X_shuf[test_cum:m]
    Y_train = Y_shuf[test_cum:m]
    
    X_tr_split = []
    Y_tr_split = []
    if n_samples_per_training_split is not None:
        n_splits = int(X_train.shape[0]/n_samples_per_training_split)
        n_splits = n_splits+1 if X_train.shape[0]%n_samples_per_training_split!=0 else n_splits
        for i in range(n_splits-1):
            X_tr_split.append(X_train[i*n_samples_per_training_split:(i+1)*n_samples_per_training_split])
            Y_tr_split.append(Y_train[i*n_samples_per_training_split:(i+1)*n_samples_per_training_split])
        X_tr_split.append(X_train[(n_splits-1)*n_samples_per_training_split:])
        Y_tr_split.append(Y_train[(n_splits-1)*n_samples_per_training_split:])
        return [[X_tr_split, X_dev, X_test],[Y_tr_split, Y_dev, Y_test],X_train.shape[0]]
    
    return [[X_train, X_dev, X_test],[Y_train, Y_dev, Y_test],X_train.shape[0]]