# Copyright 2020 Google LLC. 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 types util shared for orchestration."""
from typing import Dict, Iterable, List, Mapping, Optional

from tfx import types
from tfx.proto.orchestration import pipeline_pb2
from tfx.types import artifact_utils
from tfx.utils import json_utils
from tfx.utils import proto_utils

from google.protobuf import message
from ml_metadata.proto import metadata_store_pb2
from ml_metadata.proto import metadata_store_service_pb2


def build_artifact_dict(
    proto_dict: Mapping[str, metadata_store_service_pb2.ArtifactStructList]
) -> Dict[str, List[types.Artifact]]:
  """Converts input/output artifact dict."""
  result = {}
  for k, v in proto_dict.items():
    result[k] = []
    for artifact_struct in v.elements:
      if not artifact_struct.HasField('artifact'):
        raise RuntimeError('Only support artifact oneof field')
      artifact_and_type = artifact_struct.artifact
      result[k].append(
          artifact_utils.deserialize_artifact(artifact_and_type.type,
                                              artifact_and_type.artifact))
  return result


def build_artifact_struct_dict(
    artifact_dict: Mapping[str, Iterable[types.Artifact]]
) -> Dict[str, metadata_store_service_pb2.ArtifactStructList]:
  """Converts input/output artifact dict."""
  result = {}
  if not artifact_dict:
    return result
  for k, v in artifact_dict.items():
    artifact_list = metadata_store_service_pb2.ArtifactStructList()
    for artifact in v:
      artifact_struct = metadata_store_service_pb2.ArtifactStruct(
          artifact=metadata_store_service_pb2.ArtifactAndType(
              artifact=artifact.mlmd_artifact, type=artifact.artifact_type))
      artifact_list.elements.append(artifact_struct)
    result[k] = artifact_list
  return result


def build_value_dict(
    metadata_value_dict: Mapping[str, metadata_store_pb2.Value]
) -> Dict[str, types.Property]:
  """Converts MLMD value dict into plain value dict."""
  result = {}
  for k, v in metadata_value_dict.items():
    result[k] = getattr(v, v.WhichOneof('value'))
  return result


def build_metadata_value_dict(
    value_dict: Mapping[str, types.ExecPropertyTypes]
) -> Dict[str, metadata_store_pb2.Value]:
  """Converts plain value dict into MLMD value dict."""
  result = {}
  if not value_dict:
    return result
  for k, v in value_dict.items():
    if v is None:
      continue
    value = metadata_store_pb2.Value()
    result[k] = set_metadata_value(value, v)
  return result


def build_pipeline_value_dict(
    value_dict: Dict[str, types.ExecPropertyTypes]
) -> Dict[str, pipeline_pb2.Value]:
  """Converts plain value dict into pipeline_pb2.Value dict."""
  result = {}
  if not value_dict:
    return result
  for k, v in value_dict.items():
    if v is None:
      continue
    value = pipeline_pb2.Value()
    result[k] = set_parameter_value(value, v)
  return result


def get_parsed_value(
    value: metadata_store_pb2.Value,
    schema: Optional[pipeline_pb2.Value.Schema]) -> types.ExecPropertyTypes:
  """Converts MLMD value into parsed (non-)primitive value."""

  def parse_value(
      value: str, value_type: pipeline_pb2.Value.Schema.ValueType
  ) -> types.ExecPropertyTypes:
    if value_type.HasField('list_type'):
      list_value = json_utils.loads(value)
      return [parse_value(val, value_type.list_type) for val in list_value]
    elif value_type.HasField('proto_type'):
      return proto_utils.deserialize_proto_message(
          value, value_type.proto_type.message_type,
          value_type.proto_type.file_descriptors)
    else:
      return value