#########################################################################
#
#   Copyright 2021 VMware, Inc.  All rights reserved. VMware Confidential
#
#########################################################################
from logging import getLogger

from os.path import join
from cis.utils import readprop, write_props_to_file
from .patchUtil import TO_PREPARE_SUFFIX, updateVersion

VERSION = 4
EAM_CFG_DIR = "/etc/vmware-eam/"
EAM_VERSION = "version"
EAM_PROPS_FILE_OLD = join(EAM_CFG_DIR, "eam.properties")
EAM_PROPS_FILE_NEW = EAM_PROPS_FILE_OLD + TO_PREPARE_SUFFIX
DS_CHECK_INTERVAL_KEY = "datastores.check.interval.seconds"
DS_CHECK_INTERVAL_VAL = 900
EAM_VERSION_OLD = join(EAM_CFG_DIR, EAM_VERSION)
EAM_VERSION_NEW = join(EAM_CFG_DIR, EAM_VERSION + TO_PREPARE_SUFFIX)

_log = getLogger(__name__)


def run(ctx, isExpand):
   """
   Adds a datastores.check.interval.seconds prop and sets its value to
   eam.properties file.

   :param: ctx : B2B context
   :type: ctx : PatchContext, B2B specific structure, please refer to B2B
               documentation.
   :param: isExpand: boolean flag, True if this patch is invoked from expand
                    phase, False otherwise.
   :type: bool
   """
   file = EAM_PROPS_FILE_NEW if isExpand else EAM_PROPS_FILE_OLD
   versionFile = EAM_VERSION_NEW if isExpand else EAM_VERSION_OLD

   _log.info("Adding datastores.check.interval.seconds property\
                 to the " + file)
   try:
      interval = readprop(file, DS_CHECK_INTERVAL_KEY)

      prop = {DS_CHECK_INTERVAL_KEY: DS_CHECK_INTERVAL_VAL}
      if interval:
         try:
            int(interval)
            _log.info("The property already exists")
         except ValueError:
            _log.warn("Invalid interval value:{}".format(interval))
            replace_properties_in_file(file, prop)
            _log.info("Value updated successfully")
      else:
         write_props_to_file(file, prop.items(), mode="a+")
         _log.info("The property was added successfully")
      updateVersion(VERSION, versionFile)
   except Exception as e:
      _log.error("EAM version four patch failed.", exc_info=True)
      raise e

def updateReplicationConfig(replicationConfig):
   """
   Updates given replication config with patch specific config
   file replication configuration.

   Each item in the dictionary have following semantic:
      Key -> path of a file from source machine
      Value -> path of a file from target machine
   The file from source machine is replicated on the location pointed
   in the value over the target machine. If the Value is None, the file
   is not replicated.

   :param: replicationConfig: dictionary where to place patch specific
           config replication.
   :type: dict(str, str)
   """
   replicationConfig[EAM_VERSION_OLD] = None
   replicationConfig[EAM_VERSION_NEW] = EAM_VERSION_OLD
   replicationConfig[EAM_PROPS_FILE_OLD] = None
   replicationConfig[EAM_PROPS_FILE_NEW] = EAM_PROPS_FILE_OLD
