# Copyright (c) 2023, NVIDIA CORPORATION.  All rights reserved.
#
# 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.
"""Data source with synthetic data for testing."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function


import tensorflow as tf
from nvidia_tao_tf1.blocks.multi_source_loader.sources.data_source import (
    DataSource,
)
from nvidia_tao_tf1.core.coreobject import save_args


class SyntheticDataSource(DataSource):
    """DataSource with synthetic data."""

    @save_args
    def __init__(
        self,
        example_count,
        template=None,
        template_fn=None,
        tracker_dict=None,
        **kwargs
    ):
        """Initialize the empty Pipeline, the number of examples, and shape of the image.

        Args:
            example_count (int): number of examples to output by the dataset.
            template (T): Tensor or collection of nested tensors, copies of which will be
                generated by this data source. T must be a type supported by tf.data.Dataset.
            template_fn (function -> T): A function that returns a template. See `template`
               for description. When template is passed in via template_fn, it is guaranteed to be
               in the same graph as the tf.data.Dataset this source creates.
            tracker_dict (dict) (optional) dictionary. This data loader will set "call_count"
               field in the dictionary. Useful for tests.
        """
        super(SyntheticDataSource, self).__init__(**kwargs)
        if template is None and template_fn is None:
            raise ValueError("Template value or template_fn not specified.")

        self._example_count = example_count
        self._template = template
        self._template_fn = template_fn
        self._tracker_dict = tracker_dict

    def __len__(self):
        """Return the number of synthetic examples."""
        return self._example_count

    @property
    def parse_example(self):
        """Parse example."""
        return lambda dataset: dataset

    def call(self):
        """
        Return a tf.data.Dataset with synthetic data.

        Returns:
            (tf.data.Dataset<T>): Dataset that yields example_count copies of the template value
                provided in the constructor.
        """
        if self._template_fn:
            ds = tf.data.Dataset.from_tensors(self._template_fn())
        else:
            ds = tf.data.Dataset.from_tensors(self._template)

        def _update_tracker():
            """Updated call_count field tracker_dict by 1."""
            self._tracker_dict["call_count"] = (
                self._tracker_dict.get("call_count", 0) + 1
            )
            return self._tracker_dict["call_count"]

        def _map(x):
            tf.compat.v1.py_func(_update_tracker, [], (tf.int64))
            return x

        if self._tracker_dict is not None:
            ds = ds.map(_map)
        return ds.repeat(self._example_count)

    @property
    def image_dtype(self):
        """Return the default dtype of images."""
        return tf.float32
