# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
import logging

from dateutil.tz import tz

from c7n.exceptions import PolicyValidationError
from c7n.policy import execution, ServerlessExecutionMode, PullMode
from c7n.utils import local_session, type_schema

from c7n_gcp import mu

DEFAULT_REGION = 'us-central1'


class FunctionMode(ServerlessExecutionMode):

    schema = type_schema(
        'gcp',
        **{'execution-options': {'$ref': '#/definitions/basic_dict'},
           'timeout': {'type': 'string'},
           'memory-size': {'type': 'integer'},
           'labels': {'$ref': '#/definitions/string_dict'},
           'network': {'type': 'string'},
           'max-instances': {'type': 'integer'},
           'service-account': {'type': 'string'},
           'environment': {'$ref': '#/definitions/string_dict'}}
    )

    def __init__(self, policy):
        self.policy = policy
        self.log = logging.getLogger('custodian.gcp.funcexec')
        self.region = policy.options.regions[0] if len(policy.options.regions) else DEFAULT_REGION

    def run(self):
        raise NotImplementedError("subclass responsibility")

    def provision(self):
        self.log.info("Provisioning policy function %s", self.policy.name)
        manager = mu.CloudFunctionManager(self.policy.session_factory, self.region)
        return manager.publish(self._get_function())

    def deprovision(self):
        manager = mu.CloudFunctionManager(self.policy.session_factory, self.region)
        return manager.remove(self._get_function())

    def validate(self):
        pass

    def _get_function(self):
        raise NotImplementedError("subclass responsibility")


@execution.register('gcp-periodic')
class PeriodicMode(FunctionMode, PullMode):
    """Deploy a policy as a Cloud Functions triggered by Cloud Scheduler
    at user defined cron interval via Pub/Sub.

    Default region the function is deployed to is ``us-central1``. In
    case you want to change that, use the cli ``--region`` flag.
    """

    schema = type_schema(
        'gcp-periodic',