# Copyright 2016 Google Inc. 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.

"""Common utility functions for sql instances."""

import argparse
from googlecloudsdk.api_lib.sql import constants
from googlecloudsdk.calliope import arg_parsers
from googlecloudsdk.calliope import exceptions


# TODO(b/35104889): Migrate methods containing Namespace args to command_lib
class _BaseInstances(object):
  """Common utility functions for sql instances."""

  @classmethod
  def _SetBackupConfiguration(cls, sql_messages, settings, args, original):
    """Sets the backup configuration for the instance."""
    # create defines '--backup' while patch defines '--no-backup'
    no_backup = getattr(args, 'no_backup', False) or (
        not getattr(args, 'backup', True))

    if original and (
        any([args.backup_start_time, args.enable_bin_log is not None,
             no_backup])):
      if original.settings.backupConfiguration:
        if isinstance(original.settings.backupConfiguration, list):
          # Only one backup configuration was ever allowed.
          # Field switched from list to single object in v1beta4.
          backup_config = original.settings.backupConfiguration[0]
        else:
          backup_config = original.settings.backupConfiguration
      else:
        backup_config = sql_messages.BackupConfiguration(
            startTime='00:00',
            enabled=False),
    elif not any([args.backup_start_time, args.enable_bin_log is not None,
                  no_backup]):
      return

    if not original:
      backup_config = sql_messages.BackupConfiguration(
          startTime='00:00',
          enabled=False)

    if args.backup_start_time:
      backup_config.startTime = args.backup_start_time
      backup_config.enabled = True
    if no_backup:
      if args.backup_start_time or args.enable_bin_log is not None:
        raise exceptions.ToolException(
            ('Argument --no-backup not allowed with'
             ' --backup-start-time or --enable-bin-log'))
      backup_config.enabled = False

    if args.enable_bin_log is not None:
      backup_config.binaryLogEnabled = args.enable_bin_log

    cls.AddBackupConfigToSettings(settings, backup_config)

  @staticmethod
  def _SetDatabaseFlags(sql_messages, settings, args):
    if args.database_flags:
      settings.databaseFlags = []
      for (name, value) in args.database_flags.items():
        settings.databaseFlags.append(sql_messages.DatabaseFlags(
            name=name,
            value=value))
    elif getattr(args, 'clear_database_flags', False):
      settings.databaseFlags = []

  @staticmethod
  def _SetMaintenanceWindow(sql_messages, settings, args, original):
    """Sets the maintenance window for the instance."""