#!/usr/bin/python3
#
# Copyright (c) 2019, 2020  Peter Pentchev <roam@ringlet.net>
# All rights reserved.
#
# 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.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.

"""Encode a Python confget test data structure into a JSON file."""

import json

from typing import Any, Dict

from unit_tests.data import data as t_data
from unit_tests.data import defs as t_defs


class TestEncoder(json.JSONEncoder):
    """ Encode the confget test data into serializable objects. """

    def encode_test_file_def(self, obj: t_defs.TestFileDef) -> Dict[str, Any]:
        """ Encode a full TestFileDef object. """
        return {
            'format': {
                'version': {
                    'major': 1,
                    'minor': 0,
                },
            },
            'setenv': obj.setenv,
            'tests': [self.default(test) for test in obj.tests],
        }

    def encode_test_def(self, obj: t_defs.TestDef) -> Dict[str, Any]:
        """ Encode a single test definition. """
        return {
            'args': obj.args,
            'keys': obj.keys,
            'xform': obj.xform,
            'backend': obj.backend,
            'output': self.default(obj.output),
            'setenv': obj.setenv,
            'stdin': obj.stdin,
        }

    def encode_exact_output_def(self, obj: t_defs.TestExactOutputDef
                                ) -> Dict[str, str]:
        """ Encode an exact output requirement. """
        return {
            'exact': obj.exact,
        }

    def encode_exit_ok_output_def(self, obj: t_defs.TestExitOKOutputDef
                                  ) -> Dict[str, bool]:
        """ Encode an exit code requirement. """
        return {
            'exit': obj.success,
        }

    SERIALIZERS = {
        t_defs.TestFileDef: encode_test_file_def,
        t_defs.TestDef: encode_test_def,
        t_defs.TestExactOutputDef: encode_exact_output_def,
        t_defs.TestExitOKOutputDef: encode_exit_ok_output_def,
    }

    def default(self, obj: Any) -> Any:
        """ Meow. """
        method = self.SERIALIZERS.get(type(obj), None)
        if method is not None:
            return method(self, obj)
        return super(TestEncoder, self).default(obj)


def main() -> None:
    """ Main function: encode, output. """
    for name, tdef in sorted(t_data.TESTS.items()):
        print(f'--- {name} ---')
        with open(f'output/{name}.json', mode='w') as outf:
            print(json.dumps(tdef, indent=2, cls=TestEncoder), file=outf)


if __name__ == '__main__':
    main()
