#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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.
#
"""See docstring for PropertiesWriter class."""

# Disabling warnings for env members and imports that only affect recipe-
# specific processors.
# pylint: disable=e1101,f0401

from __future__ import absolute_import

import ConfigParser
from collections import OrderedDict

from autopkglib import Processor, ProcessorError

__all__ = ["PropertiesWriter"]


# this code stolen from http://stackoverflow.com/a/25084055
class EqualsSpaceRemover:
    output_file = None

    def __init__(self, new_output_file):
        self.output_file = new_output_file

    def write(self, what):
        self.output_file.write(what.replace(" = ", "="))


class PropertiesWriter(Processor):
    # pylint: disable=missing-docstring
    description = "Read the version.properties file inside the SQLDeveloper.app."
    input_variables = {
        "file_path": {
            "required": True,
            "description": "Path to source.properties file to create.",
        },
        "properties": {
            "required": True,
            "description": "Dictionary of keys/values to write to file.",
        },
    }
    output_variables = {}

    __doc__ = description

    def main(self):
        cp = ConfigParser.SafeConfigParser()
        cp.optionxform = str

        sort = sorted(self.env["properties"].items(), key=lambda t: t[0])
        properties = OrderedDict(sort)

        for key, value in properties.iteritems():
            cp.set("", str(key), value)
        # Write the file out
        with open(self.env["file_path"], "wb") as f:
            try:
                cp.write(EqualsSpaceRemover(f))
            except IOError as err:
                raise ProcessorError(err)
        # Now delete the first line, the section header
        with open(self.env["file_path"], "rb") as old:
            lines = old.readlines()
        lines[0] = "# Generated by AutoPkg\n"
        with open(self.env["file_path"], "wb") as new:
            for line in lines:
                new.write(line)


if __name__ == "__main__":
    PROCESSOR = PropertiesWriter()
    PROCESSOR.execute_shell()
