#!/usr/bin/env python
#
# Copyright 2017-2019 VMware, Inc.  All rights reserved. -- VMware Confidential
#

import logging
import os
import re
import sys

sys.path.append(os.environ['VMWARE_PYTHON_PATH'])

from cis.utils import FileBuffer

logger = logging.getLogger(__name__)


def text_subst_in_file(file_path, text_subst_args):
    """
    Replace strings in a file

    :param file_path: Path to the file
    :type file_path: str

    :param text_subst_args: Object with key - the string to search and value - string to replace with
    :type text_subst_args: object
    """

    logger.info('Replacing values in file %s' % file_path)
    with open(file_path) as f:
        file_content = f.read()

    for k, v in text_subst_args.items():
        file_content = file_content.replace(k, v)

    with open(file_path, 'w') as f:
        f.write(file_content)

    logger.info('Done')


def get_service_id(cisreg_spec_file):
    """
    Get the value of cmreg.serviceid property from the service registration spec file

    :param cisreg_spec_file: Path to the service registration spec file
    :type cisreg_spec_file: str

    :return: The service registration id or None
    :rtype: str
    """
    file_buffer = FileBuffer()
    file_buffer.readFile(cisreg_spec_file)
    serviceId = get_property(file_buffer, 'cmreg.serviceid')
    return serviceId


def get_property(file_buffer, key):
    """
    Get the value of a property from a file with properties

    :param file_buffer: File buffer with the properties file contents
    :type file_buffer: FileBuffer

    :param key: The property name
    :type key: str

    :return: The value of the property or None
    :rtype: str
    """
    pat = r'^(\s*' + re.escape(key) + r'\s*=\s*)(.*)'
    for line in file_buffer.getBufferContents():
        m = re.search(pat, line)
        if m:
            return m.group(2).strip()
    return None

# ----
# Add or update a key value pair in a given file
# ----
def add_or_update_property_in_file(fileName, key, value):
   f = FileBuffer()
   try:
      f.readFile(fileName)
      f.addOrUpdateProps({key: value})
      f.writeFile(fileName)
   finally:
      f.clearBuffer()

def get_property_from_file(fileName, prop):
    f = FileBuffer()
    try:
        f.readFile(fileName)
        value = get_property(f, prop)
    finally:
        f.clearBuffer()
    return value

def read_properties(prop_file_path):
   """
   Given the path of a properties file, reads all properties
   from the file into a dictionary

   :param prop_file_path: the path of the properties file

   :return a dictionary whose keys are the property names,
           and whose values are the property values
   :rtype dictionary
   """
   props = {}
   with open(prop_file_path, "r") as f:
      for line in f:
         if not line.startswith("#"):
            (name, value) = line.split('=')
            props[name.strip()] = value.strip()
   return props

def write_properties(prop_file_path, props):
   """
   Writes the content of the props dictionary into a file. If the file
   already exists, it will be overwritten.

   :param prop_file_path: the file path where the props dictionary
          should be written
   :param props: the dictionary whose content should be written to the file
   """
   with open(prop_file_path, "w") as f:
      for name, value in props.items():
         f.write(name + " = " + value + "\n")
