# coding: utf-8
"""Work with video objects via the Supervisely API."""

# docs
from typing import List, Optional

from supervisely.api.entity_annotation.object_api import ObjectApi
from supervisely.api.video.video_tag_api import VideoObjectTagApi
from supervisely.video_annotation.key_id_map import KeyIdMap
from supervisely.video_annotation.video_object_collection import VideoObjectCollection


class VideoObjectApi(ObjectApi):
    """
    API for working with video objects.
    """

    def __init__(self, api):
        """
        :param api: :class:`~supervisely.api.api.Api` object to use for API connection.
        :type api: :class:`~supervisely.api.api.Api`
        """
        super().__init__(api)
        self.tag = VideoObjectTagApi(api)

    def append_bulk(
        self,
        video_id: int,
        objects: VideoObjectCollection,
        key_id_map: Optional[KeyIdMap] = None,
    ) -> List[int]:
        """
        Add objects to annotation objects.

        :param video_id: Video ID in Supervisely.
        :type video_id: int
        :param objects: VideoObjectCollection objects collection.
        :type objects: :class:`~supervisely.video_annotation.video_object_collection.VideoObjectCollection`
        :param key_id_map: KeyIdMap object.
        :type key_id_map: :class:`~supervisely.video_annotation.key_id_map.KeyIdMap`, optional
        :returns: List of object IDs
        :rtype: List[int]

        :Usage Example:

            .. code-block:: python

                import os
                from dotenv import load_dotenv

                import supervisely as sly
                from supervisely.video_annotation.key_id_map import KeyIdMap

                # Load secrets and create API object from .env file (recommended)
                # Learn more here: https://developer.supervisely.com/getting-started/basics-of-authentication
                if sly.is_development():
                    load_dotenv(os.path.expanduser("~/supervisely.env"))

                api = sly.Api.from_env()

                project_id = 17209
                video_id = 19402023

                meta_json = api.project.get_meta(project_id)
                project_meta = sly.ProjectMeta.from_json(meta_json)

                key_id_map = KeyIdMap()
                ann_info = api.video.annotation.download(video_id)
                ann = sly.VideoAnnotation.from_json(ann_info, project_meta, key_id_map)

                api.video.object.append_bulk(video_id, ann.objects, key_id_map)
        """

        info = self._api.video.get_info_by_id(video_id)
        return self._append_bulk(
            self._api.video.tag, video_id, info.project_id, info.dataset_id, objects, key_id_map
        )
