"""
MIT License

Copyright (c) 2022 Author(s)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import tensorflow as tf
import tensorflow_datasets as tfds

def load_mnist(preproc, batch_size, data_dir):
    """
    - Args
    preproc: A preprocessing function with arguments x and data_format.
      E.g., tf.keras.applications.resnet_v2.preprocess_input.
      # Args
      x: A floating point numpy.array or a tf.Tensor, 3D or 4D with 
        3 color channels, with values in the range [0, 255]. 
        The preprocessed data are written over the input data 
        if the data types are compatible. To avoid this behaviour,
        numpy.copy(x) can be used.
      data_format: Optional data format of the image tensor/array. 
        Defaults to None, in which case the global setting 
        tf.keras.backend.image_data_format() is used 
        (unless you changed it, it defaults to "channels_last").
    batch_size: Int. Batch size.
    data_dir: Str. Dataset will be donwloaed here.
      E.g., "/data/tensorflow_datasets"
    - Return
    dstr: Training dataset.
    """
    # Load dataset
    dstr, _ = tfds.load(
        "mnist", 
        data_dir=data_dir, 
        split=["train", "test"])
        # shuffle_files=False, bathch_size=None here 
        # because dataset.shuffle and .batch is more customizable.
        
    # Dataset decoration
    # map -> cache -> shuffle -> batch -> prefetch with AUTOTUNE
    # Ref: https://www.tensorflow.org/tutorials/load_data/images#configure_the_dataset_for_performance
    dstr = dstr.map(
        lambda x: (tf.cast(x["image"], dtype=tf.keras.backend.floatx()), x["label"])) # no AUTOTUNE
    dstr = dstr.map(
        lambda x, y: (preproc(x), y)) # no AUTOTUNE
    dstr = dstr.cache() 
    dstr = dstr.batch(batch_size=batch_size, drop_remainder=False) # no AUTOTUNE in .batch in TF2.3
    dstr = dstr.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
    return dstr
