##############################################################################
#
# Copyright (c) 2013 Nexedi SA and Contributors. All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is free software: you can Use, Study, Modify and Redistribute
# it under the terms of the GNU General Public License version 3, or (at your
# option) any later version, as published by the Free Software Foundation.
#
# You can also Link and Combine this program with other software covered by
# the terms of any of the Free Software licenses or any of the Open Source
# Initiative approved licenses and Convey the resulting work. Corresponding
# source of such a combination shall include the source code for all other
# software used.
#
# This program is distributed WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See COPYING file for full licensing terms.
# See https://www.nexedi.com/licensing for rationale and options.
#
##############################################################################

import ConfigParser
import os
import zc.buildout

from slapos.recipe.librecipe import GenericBaseRecipe


class WriteRecipe(GenericBaseRecipe):
  """
  """
  def __init__(self, buildout, name, options):
    if not "filename" in options and not "file-path" in options:
      raise zc.buildout.UserError("You have to provide the parameter either \"filename\" or \"file-path\"")

    self._options = options.copy()
    if options.get('filename'):
      self.filename = options['filename'].strip()
      self.path = os.path.join(buildout['buildout']['directory'], self.filename)
      del self._options['filename']
    else:
      self.path = options['file-path'].strip()
      del self._options['file-path']
    del self._options['recipe']
    self.name = name

  def install(self):

    # Set up the parser, and write config file if needed
    self.parser = ConfigParser.ConfigParser()
    try:
      self.parser.read(self.path)
      #clean_options(options)
      for key in self._options:
        if key not in self.parser.options(self.name):
          self.parser.set(self.name, key, self._options[key])
      with open(self.path, 'w') as file:
        self.parser.write(file)
    # If the file or section do not exist
    except (ConfigParser.NoSectionError, IOError) as e:
      self.full_install()

  def full_install(self):
    """XXX-Nicolas : when some parameter's value is changed in
    buildout profile, this will override custom user defined values"""
    self.parser.read(self.path)
    if self.parser.has_section(self.name):
      self.parser.remove_section(self.name)
    self.parser.add_section(self.name)
    for key in self._options:
      self.parser.set(self.name, key, self._options[key])
    with open(self.path, 'w') as file:
      self.parser.write(file)

  update = install

class ReadRecipe(GenericBaseRecipe):
  """
  """
  def __init__(self, buildout, name, options):
    if not "filename" in options and not "file-path" in options:
      raise zc.buildout.UserError("You have to provide the parameter either \"filename\" or file-path")

    if options.get('filename'):
      self.filename = options['filename'].strip()
      self.path = os.path.join(buildout['buildout']['directory'], self.filename)
    else:
      self.path = options['file-path'].strip()

    # Set up the parser, and write config file if needed
    self.parser = ConfigParser.ConfigParser()
    if os.path.exists(self.path):
      self.parser.read(self.path)
      for section in self.parser.sections():
        for key ,value in self.parser.items(section):
            options[key] = value

  install = update = lambda self: []
