#!/usr/bin/python
# Copyright 2016 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# gen_format_map.py:
#  Code generation for GL format map. The format map matches between
#  {format,type} and internal format.

from datetime import date
import sys

sys.path.append('renderer')
import angle_format

template_cpp = """// GENERATED FILE - DO NOT EDIT.
// Generated by {script_name} using data from {data_source_name}.
//
// Copyright {copyright_year} The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// format_map:
//   Determining the sized internal format from a (format,type) pair.

#include "angle_gl.h"
#include "common/debug.h"

namespace gl
{{

GLenum GetSizedFormatInternal(GLenum format, GLenum type)
{{
    switch (format)
    {{
{format_cases}        case GL_NONE:
            return GL_NONE;

        default:
            break;
    }}

    return GL_NONE;
}}

}}  // namespace gl
"""

template_format_case = """        case {format}:
            switch (type)
            {{
{type_cases}                default:
                    break;
            }}
            break;

"""

template_type_case = """                case {type}:
                    return {internal_format};
"""

def parse_type_case(type, internal_format):
    return template_type_case.format(
        type = type, internal_format = internal_format)

def parse_format_case(format, type_map):
    type_cases = ""
    for type, internal_format in sorted(type_map.iteritems()):
        type_cases += parse_type_case(type, internal_format)
    return template_format_case.format(
        format = format, type_cases = type_cases)

input_script = 'format_map_data.json'

format_map = angle_format.load_json(input_script)

format_cases = ""

for format, type_map in sorted(format_map.iteritems()):
    format_cases += parse_format_case(format, type_map)

with open('format_map_autogen.cpp', 'wt') as out_file:
    output_cpp = template_cpp.format(
        script_name = sys.argv[0],
        data_source_name = input_script,
        copyright_year = date.today().year,
        format_cases = format_cases)
    out_file.write(output_cpp)
    out_file.close()
