# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Monster-Monash custom downloader"""


import numpy as np
import os
import datasets


_DATASET = "AudioMNIST-DS"
_SHAPE = (1, 4000)
#_DESCRIPTION = ""
#_CITATION = ""
#_HOMEPAGE = ""
#_LICENSE = ""

_URLS = {
    'data': f"{_DATASET}_X.npy",
    'labels': f"{_DATASET}_y.npy",
    'fold_0': "test_indices_fold_0.txt",
    'fold_1': "test_indices_fold_1.txt",
    'fold_2': "test_indices_fold_2.txt",
    'fold_3': "test_indices_fold_3.txt",
    'fold_4': "test_indices_fold_4.txt",
    }


class Monster(datasets.GeneratorBasedBuilder):
    """Generic Monster class for all downloader."""

    VERSION = datasets.Version("1.0.0")

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="full", version=VERSION, description="All data"),
        datasets.BuilderConfig(name="fold_0", version=VERSION, description="Cross-validation fold 0"),
        datasets.BuilderConfig(name="fold_1", version=VERSION, description="Cross-validation fold 1"),
        datasets.BuilderConfig(name="fold_2", version=VERSION, description="Cross-validation fold 2"),
        datasets.BuilderConfig(name="fold_3", version=VERSION, description="Cross-validation fold 3"),
        datasets.BuilderConfig(name="fold_4", version=VERSION, description="Cross-validation fold 4"),
    ]

    DEFAULT_CONFIG_NAME = "full"  # By default all data is returned in a single split.

    def _info(self):
        features = datasets.Features(
            {
                "X": datasets.Array2D(_SHAPE, "float32"),
                "y": datasets.Value("int64")
            }
        )
        return datasets.DatasetInfo(
#            description=_DESCRIPTION,
            features=features,
            supervised_keys=("X", "y"),
#            homepage=_HOMEPAGE,
#            license=_LICENSE,
#            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        data = dl_manager.download_and_extract(_URLS['data'])
        labels = dl_manager.download_and_extract(_URLS['labels'])
        if self.config.name == "full":
            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TRAIN,
                    gen_kwargs={
                        "data": data,
                        "labels": labels,
                        "fold": None,
                        "split": "all",
                    },
                ),
            ]
        else: 
            fold = dl_manager.download_and_extract(_URLS[self.config.name])
            return [
                datasets.SplitGenerator(
                    name=datasets.Split.TRAIN,
                    gen_kwargs={
                        "data": data,
                        "labels": labels,
                        "fold": fold,
                        "split": "train",
                    },
                ),
                datasets.SplitGenerator(
                    name=datasets.Split.TEST,
                    gen_kwargs={
                        "data": data,
                        "labels": labels,
                        "fold": fold,
                        "split": "test"
                    },
                ),
            ]

    def _generate_examples(self, data, labels, fold, split):
        X = np.load(data)
        y = np.load(labels)
        if self.config.name == "full":
            for row in range(y.shape[0]):
                yield(row, {"X": X[row], "y": y[row]})
        else:
            test_indices = np.loadtxt(fold, dtype='int')
            if split == "test":
                for row in test_indices:
                    yield(int(row), {"X": X[row], "y": y[row]})
            elif split == "train":
                train_indices = np.delete(np.arange(y.shape[0]), test_indices)
                for row in train_indices:
                    yield(int(row), {"X": X[row], "y": y[row]})