#!/usr/bin/env python

copyright = """/*
 * Copyright (C) 2014 BlueKitchen GmbH
 *
 * 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 the copyright holders nor the names of
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 * 4. Any redistribution, use, or modification is done solely for
 *    personal benefit and not for any commercial purpose or for
 *    monetary gain.
 *
 * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH 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 MATTHIAS
 * RINGWALD 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.
 *
 * Please inquire about commercial licensing options at 
 * contact@bluekitchen-gmbh.com
 *
 */
"""

hfile_header_begin = """

/*
 *  btstack_memory.h
 *
 *  @brief BTstack memory management via configurable memory pools
 *
 */

#ifndef __BTSTACK_MEMORY_H
#define __BTSTACK_MEMORY_H

#if defined __cplusplus
extern "C" {
#endif

#include "btstack-config.h"
    
#include "hci.h"
#include "l2cap.h"
#include "rfcomm.h"
#include "bnep.h"
#include "hfp.h"
#include "remote_device_db.h"

#ifdef HAVE_BLE
#include "gatt_client.h"
#include "sm.h"
#endif

/* API_START */

/**
 * @brief Initializes BTstack memory pools.
 */
void btstack_memory_init(void);

/* API_END */
"""

hfile_header_end = """
#if defined __cplusplus
}
#endif

#endif // __BTSTACK_MEMORY_H
"""

cfile_header_begin = """
/*
 *  btstsack_memory.h
 *
 *  @brief BTstack memory management via configurable memory pools
 *
 *  @note code semi-atuomatically generated by tools/btstack_memory_generator.py
 *
 */

#include "btstack_memory.h"
#include <btstack/memory_pool.h>

#include <stdlib.h>

"""

header_template = """STRUCT_NAME_t * btstack_memory_STRUCT_NAME_get(void);
void   btstack_memory_STRUCT_NAME_free(STRUCT_NAME_t *STRUCT_NAME);"""

code_template = """
// MARK: STRUCT_TYPE
#ifdef POOL_COUNT
#if POOL_COUNT > 0
static STRUCT_TYPE STRUCT_NAME_storage[POOL_COUNT];
static memory_pool_t STRUCT_NAME_pool;
STRUCT_NAME_t * btstack_memory_STRUCT_NAME_get(void){
    return (STRUCT_NAME_t *) memory_pool_get(&STRUCT_NAME_pool);
}
void btstack_memory_STRUCT_NAME_free(STRUCT_NAME_t *STRUCT_NAME){
    memory_pool_free(&STRUCT_NAME_pool, STRUCT_NAME);
}
#else
STRUCT_NAME_t * btstack_memory_STRUCT_NAME_get(void){
    return NULL;
}
void btstack_memory_STRUCT_NAME_free(STRUCT_NAME_t *STRUCT_NAME){
    // silence compiler warning about unused parameter in a portable way
    (void) STRUCT_NAME;
};
#endif
#elif defined(HAVE_MALLOC)
STRUCT_NAME_t * btstack_memory_STRUCT_NAME_get(void){
    return (STRUCT_NAME_t*) malloc(sizeof(STRUCT_TYPE));
}
void btstack_memory_STRUCT_NAME_free(STRUCT_NAME_t *STRUCT_NAME){
    free(STRUCT_NAME);
}
#else
#error "Neither HAVE_MALLOC nor POOL_COUNT for struct STRUCT_NAME is defined. Please, edit the config file."
#endif
"""

init_template = """#if POOL_COUNT > 0
    memory_pool_create(&STRUCT_NAME_pool, STRUCT_NAME_storage, POOL_COUNT, sizeof(STRUCT_TYPE));
#endif"""

def writeln(f, data):
    f.write(data + "\n")

def replacePlaceholder(template, struct_name):
    struct_type = struct_name + '_t'
    if struct_name.endswith('try'):
        pool_count = "MAX_NO_" + struct_name.upper()[:-3] + "TRIES"
    else:
        pool_count = "MAX_NO_" + struct_name.upper() + "S"
    
    snippet = template.replace("STRUCT_TYPE", struct_type).replace("STRUCT_NAME", struct_name).replace("POOL_COUNT", pool_count)
    return snippet
    
list_of_structs = [ ["hci_connection"], ["l2cap_service", "l2cap_channel"], ["rfcomm_multiplexer", "rfcomm_service", "rfcomm_channel"], ["db_mem_device_name", "db_mem_device_link_key", "db_mem_service"], ["bnep_service", "bnep_channel"], ["hfp_connection"]]
list_of_le_structs = [["gatt_client", "gatt_subclient", "whitelist_entry", "sm_lookup_entry"]]

file_name = "../src/btstack_memory"


f = open(file_name+".h", "w")
writeln(f, copyright)
writeln(f, hfile_header_begin)
for struct_names in list_of_structs:
    writeln(f, "// "+ ", ".join(struct_names))
    for struct_name in struct_names:
        writeln(f, replacePlaceholder(header_template, struct_name))
    writeln(f, "")
writeln(f, "#ifdef HAVE_BLE")
for struct_names in list_of_le_structs:
    writeln(f, "// "+ ", ".join(struct_names))
    for struct_name in struct_names:
        writeln(f, replacePlaceholder(header_template, struct_name))
writeln(f, "#endif")
writeln(f, hfile_header_end)
f.close();


f = open(file_name+".c", "w")
writeln(f, copyright)
writeln(f, cfile_header_begin)
for struct_names in list_of_structs:
    for struct_name in struct_names:
        writeln(f, replacePlaceholder(code_template, struct_name))
    writeln(f, "")
writeln(f, "#ifdef HAVE_BLE")
for struct_names in list_of_le_structs:
    for struct_name in struct_names:
        writeln(f, replacePlaceholder(code_template, struct_name))
    writeln(f, "")
writeln(f, "#endif")


writeln(f, "// init")
writeln(f, "void btstack_memory_init(void){")
for struct_names in list_of_structs:
    for struct_name in struct_names:
        writeln(f, replacePlaceholder(init_template, struct_name))
writeln(f, "#ifdef HAVE_BLE")
for struct_names in list_of_le_structs:
    for struct_name in struct_names:
        writeln(f, replacePlaceholder(init_template, struct_name))
writeln(f, "#endif")
writeln(f, "}")
f.close();
    
