# Copyright (c) 2016, Samantha Marshall (http://pewpewthespells.com)
# All rights reserved.
#
# https://github.com/samdmarshall/pyconfig
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# 3. Neither the name of Samantha Marshall nor the names of its contributors may
# be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
# OF THE POSSIBILITY OF SUCH DAMAGE.

import os
from ..Keyword.ExportKeyword      import ExportKeyword
from ..version                    import __version__ as PYCONFIG_VERSION
from ..Helpers.Logger             import Logger

def openOutputFileToWrite(input_string):
    """
    Takes a path to the output file as a string and returns an open
    writeable file. The path will be expanded and parent directories
    will be created if necessary.
    """
    file_path = os.path.expanduser(input_string)
    parent_path = os.path.dirname(file_path)
    if not os.path.exists(parent_path):  # pragma: no cover
        try:
            os.makedirs(parent_path)
        except OSError as error:
            if error.errno != 17:
                raise
    return open(file_path, 'w')

def writeFile(config_node=None, scheme_name=None):
    """
    Takes a configuration file node object and a string of the scheme
    name and will write out a file to disk.
    """
    pyconfig_contents = config_node.config
    config_file_path = config_node.name

    output_file_path = config_node.exportPath()

    common_file_prefix = os.path.commonprefix([os.path.dirname(output_file_path), os.path.dirname(config_file_path)])
    origin_file_path = os.path.relpath(config_file_path, start=common_file_prefix)
    output_rel_file_path = os.path.relpath(output_file_path, start=common_file_prefix)

    # Log that the input and output paths have been determined, letting the user
    ## know where to expect the files to be written.
    Logger.write().info('Serializing %s -> %s' % (origin_file_path, output_rel_file_path))

    # open the file so that it can be written to
    output_file = openOutputFileToWrite(output_file_path)
    output_file.write('// Generated by pyconfig ' + PYCONFIG_VERSION + '\n')
    output_file.write('// From file: ' + origin_file_path + '\n')

    if scheme_name:
        output_file.write('SCHEME_NAME = ' + scheme_name + '\n')

    for item in pyconfig_contents:
        if isinstance(item, ExportKeyword):
            continue

        Logger.write().debug('Attempting to serialize: %s' % item)
        line_string = item.serialize()

        log_string = ''
        for line in line_string.split('\n'):
            if len(line):
                log_string += '\n> '+line
        Logger.write().debug('Serializing: %s' % log_string)

        output_file.write(line_string)

    # close the file now that the entire configuration has been written
    output_file.close()
