#!/usr/bin/python
#
# Copyright 2018-2023 Polyaxon, Inc.
#
# 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.
from typing import Dict, List, Optional, Union

from pydantic import Field, StrictStr, validator

from polyaxon.containers.pull_policy import PullPolicy
from polyaxon.k8s import k8s_schemas, k8s_validation
from polyaxon.schemas.base import BaseSchemaModel


class BaseServiceConfig(BaseSchemaModel):
    _SWAGGER_FIELDS = {
        "resources",
        "affinity",
        "tolerations",
    }

    image: Optional[StrictStr]
    image_tag: Optional[StrictStr] = Field(alias="imageTag")
    image_pull_policy: Optional[PullPolicy] = Field(alias="imagePullPolicy")
    resources: Optional[Union[k8s_schemas.V1ResourceRequirements, Dict]]
    node_selector: Optional[Dict[StrictStr, StrictStr]] = Field(alias="nodeSelector")
    affinity: Optional[Union[k8s_schemas.V1Affinity, Dict]]
    tolerations: Optional[List[Union[k8s_schemas.V1Toleration, Dict]]]
    image_pull_secrets: Optional[List[StrictStr]] = Field(alias="imagePullSecrets")
    hpa: Optional[Dict]

    @validator("resources", always=True, pre=True)
    def validate_resources(cls, v):
        return k8s_validation.validate_k8s_resource_requirements(v)

    @validator("affinity", always=True, pre=True)
    def validate_affinity(cls, v):
        return k8s_validation.validate_k8s_affinity(v)

    @validator("tolerations", always=True, pre=True)
    def validate_tolerations(cls, v):
        if not v:
            return v
        return [k8s_validation.validate_k8s_toleration(vi) for vi in v]
