def format_doc(packet):
    text = common.select_lang(packet.get_doc()[1])
    link = '{{@link {0}{1}#{2}({3})}}'
    link_c = '{{@link {0}{1}.{2}Listener}}'

    # handle tables
    lines = text.split('\n')
    replaced_lines = []
    in_table_head = False
    in_table_body = False

    for line in lines:
        if line.strip() == '.. csv-table::':
            in_table_head = True
            replaced_lines.append('\\verbatim')
        elif line.strip().startswith(':header: ') and in_table_head:
            replaced_lines.append(line[len(':header: '):])
        elif line.strip().startswith(':widths:') and in_table_head:
            pass
        elif len(line.strip()) == 0 and in_table_head:
            in_table_head = False
            in_table_body = True

            replaced_lines.append('')
        elif len(line.strip()) == 0 and in_table_body:
            in_table_body = False

            replaced_lines.append('\\endverbatim')
            replaced_lines.append('')
        else:
            replaced_lines.append(line)

    text = '\n'.join(replaced_lines)

    cls = device.get_camel_case_name()
    for other_packet in device.get_packets():
        name_false = ':func:`{0}`'.format(other_packet.get_camel_case_name())
        if other_packet.get_type() == 'callback':
            name = other_packet.get_camel_case_name()
            name_right = link_c.format(device.get_category(), cls, name)
        else:
            name = other_packet.get_headless_camel_case_name()
            name_right = link.format(device.get_category(), cls, name,
                                     java_common.make_parameter_list(other_packet, True))

        text = text.replace(name_false, name_right)

    text = text.replace(":word:`parameter`", "parameter")
    text = text.replace(":word:`parameters`", "parameters")
    text = text.replace('Callback ', 'Listener ')
    text = text.replace(' Callback', ' Listener')
    text = text.replace('callback ', 'listener ')
    text = text.replace(' callback', ' listener')
    text = text.replace('.. note::', '\\note')
    text = text.replace('.. warning::', '\\warning')

    text = common.handle_rst_if(text, device)
    text = common.handle_since_firmware(text, device, packet)

    return '\n\t * '.join(text.strip().split('\n'))
def make_listener_definitions():
    cbs = ''
    cb = """
\t/**
\t * {3}
\t */
\tpublic interface {0}Listener {{
\t\tpublic void {1}({2});
\t}}
"""
    for packet in device.get_packets('callback'):
        name = packet.get_camel_case_name()
        name_lower = packet.get_headless_camel_case_name()
        parameter = java_common.make_parameter_list(packet)
        doc = format_doc(packet)
        cbs += cb.format(name, name_lower, parameter, doc)
    return cbs
def make_callbacks():
    cb = {
    'en': """
.. java:function:: public class {0}{1}.{2}Listener()

 This listener can be added with the ``add{2}Listener()`` function.
 An added listener can be removed with the ``remove{2}Listener()`` function.

 .. java:function:: public void {3}({4})
  :noindex:

{5}
""",
    'de': """
.. java:function:: public class {0}{1}.{2}Listener()

 Dieser Listener kann mit der Funktion ``add{2}Listener()`` hinzugefügt werde.
 Ein hinzugefügter Listener kann mit der Funktion ``remove{2}Listener()`` wieder
 entfernt werden.

 .. java:function:: public void {3}({4})
  :noindex:

{5}
"""
    }

    cbs = ''
    cls = device.get_camel_case_name()
    for packet in device.get_packets('callback'):
        desc = format_doc(packet, 2)
        params = java_common.make_parameter_list(packet)

        cbs += common.select_lang(cb).format(device.get_category(),
                                             cls,
                                             packet.get_camel_case_name(),
                                             packet.get_headless_camel_case_name(),
                                             params,
                                             desc)

    return cbs
def make_methods(typ):
    methods = ''
    func_start = '.. java:function:: '
    cls = device.get_category() + device.get_camel_case_name()
    for packet in device.get_packets('function'):
        if packet.get_doc()[0] != typ:
            continue

        ret_type = java_common.get_return_type(packet, True)
        name = packet.get_headless_camel_case_name()
        params = java_common.make_parameter_list(packet)
        desc = format_doc(packet, 1)
        obj_desc = make_object_desc(packet)
        func = '{0}public {1} {2}::{3}({4})\n{5}{6}'.format(func_start, 
                                                            ret_type,
                                                            cls, 
                                                            name, 
                                                            params, 
                                                            desc,
                                                            obj_desc)
        methods += func + '\n'

    return methods
def make_methods():
    methods = ''
    method = """
\t/**
\t * {8}
\t */
\tpublic {0} {1}({2}) {3} {{
\t\tByteBuffer bb = ipcon.createRequestPacket((byte){4}, FUNCTION_{5}, this);
{6}
{7}
\t}}
"""
    method_response = """\t\tbyte[] response = sendRequest(bb.array());

\t\tbb = ByteBuffer.wrap(response, 8, response.length - 8);
\t\tbb.order(ByteOrder.LITTLE_ENDIAN);

{1}
\t\treturn {2};"""

    method_noresponse = """\t\tsendRequest(bb.array());"""

    loop = """\t\tfor(int i = 0; i < {0}; i++) {{
{1}
\t\t}}
"""
    string_loop = """\t\ttry {{
\t\t{0}
\t\t\t}} catch(Exception e) {{
\t\t\t\tbb.put((byte)0);
\t\t\t}}"""

    cls = device.get_camel_case_name()
    for packet in device.get_packets('function'):
        options = 0
        ret = java_common.get_return_type(packet)
        name_lower = packet.get_headless_camel_case_name()
        parameter = java_common.make_parameter_list(packet)
        size = str(packet.get_request_length())
        name_upper = packet.get_upper_case_name()
        doc = format_doc(packet)
        bbputs = ''
        bbput = '\t\tbb.put{0}({1}{2});'
        for element in packet.get_elements('in'):
            name = common.underscore_to_headless_camel_case(element[0])
            if element[1] == 'bool':
                name = '({0} ? 1 : 0)'.format(name)

            cast = ''
            put_java_type = get_put_java_type(element[1])
            if put_java_type != java_common.get_java_type(element[1]):
                cast = '({0})'.format(put_java_type)

            bbput_format = bbput.format(get_put_type(element[1]),
                                        cast,
                                        name)

            if element[2] > 1:
                if element[1] == 'string':
                    bbput_format = bbput_format.replace(');', '.charAt(i));')
                    bbput_format = string_loop.format(bbput_format)
                else:
                    bbput_format = bbput_format.replace(');', '[i]);')
                bbput_format = loop.format(element[2], '\t' + bbput_format)

            bbputs += bbput_format + '\n'

        throw = 'throws TimeoutException, NotConnectedException'
        if len(packet.get_elements('out')) == 0:
            bbgets = ''
            bbret = ''
        elif len(packet.get_elements('out')) > 1:
            bbgets, bbret = make_bbgets(packet, True)
            obj_name = java_common.get_object_name(packet)
            obj = '\t\t{0} obj = new {0}();\n'.format(obj_name)
            bbgets = obj + bbgets
            bbret = 'obj'
        else:
            bbgets, bbret = make_bbgets(packet, False)

        if len(packet.get_elements('out')) == 0:
            response = method_noresponse.format(name_upper)
        else:
            response = method_response.format(name_upper,
                                              bbgets,
                                              bbret)

        methods += method.format(ret,
                                 name_lower,
                                 parameter,
                                 throw,
                                 size,
                                 name_upper,
                                 bbputs,
                                 response,
                                 doc)

    return methods