# Original code taken from mcuboot project at:
# https://github.com/mcu-tools/mcuboot
# Git SHA of the original version: a8e12dae381080e898cea0c6f7408009b0163f9f
#
# SPDX-License-Identifier: Apache-2.0
#
# 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.
"""General key class."""

import sys

AUTOGEN_MESSAGE = "/* Autogenerated by imgtool.py, do not edit. */"

class KeyClass(object):
    def _public_emit(self, header, trailer, indent, file=sys.stdout, len_format=None):
        print(AUTOGEN_MESSAGE, file=file)
        print(header, end='', file=file)
        encoded = self.get_public_bytes()
        for count, b in enumerate(encoded):
            if count % 8 == 0:
                print("\n" + indent, end='', file=file)
            else:
                print(" ", end='', file=file)
            print("0x{:02x},".format(b), end='', file=file)
        print("\n" + trailer, file=file)
        if len_format is not None:
            print(len_format.format(len(encoded)), file=file)

    def emit_c(self, file=sys.stdout):
        self._public_emit(
                header="const unsigned char {}_pub_key[] = {{".format(self.shortname()),
                trailer="};",
                indent="    ",
                len_format="const unsigned int {}_pub_key_len = {{}};".format(self.shortname()),
                file=file)

    def emit_rust(self, file=sys.stdout):
        self._public_emit(
                header="static {}_PUB_KEY: &'static [u8] = &[".format(self.shortname().upper()),
                trailer="];",
                indent="    ",
                file=file)
