#!/usr/bin/python3
# You may redistribute this program and/or modify it under the terms of
# the GNU General Public License as published by the Free Software Foundation,
# either version 3 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

from __future__ import print_function
from cjdnsadmin.cjdnsadmin import connectWithAdminInfo;
from cjdnsadmin.publicToIp6 import PublicToIp6_convert;

cjdns = connectWithAdminInfo();

def getLink(node, num, nodes, spaces, parentPath):
    resp = cjdns.NodeStore_getLink(node, num);
    getNode(resp[b'result'], resp[b'result'][b'cannonicalLabel'], nodes, spaces + '  ', parentPath);

def getNode(next, path, nodes, spaces, parentPath):
    if (next[b'child'] in nodes): return;
    #nodes = list(nodes);
    nodes.append(next[b'child']);
    resp = cjdns.NodeStore_nodeForAddr(next[b'child']);
    #print 'cjdns.NodeStore_getNode(' + next['child'] + '); --> ' + str(resp);
    #next['child'] = PublicToIp6_convert(resp['result']['key']);
    path = b''
    if (parentPath != b'ffff.ffff.ffff.ffff' and len(parentPath) == 19):
        p = cjdns.NodeStore_getRouteLabel(parentPath, next[b'child']);
        if p[b'error'] != b'none':
            path = p[b'error'].decode()+'  '+str([s.decode() for s in nodes]);
            print('cjdns.NodeStore_getRouteLabel(' + parentPath.decode() + ',',
                next[b'child'].decode() + '); --> ' + path)
            exit(1);
        else: path = p[b'result']
    print(spaces + str(next[b'child']) + '  ' + str(next[b'cannonicalLabel']) + " -> " + path.decode())
    #print str(resp['result']) + ',';
    for i in range(0, int(resp[b'result'][b'linkCount'])):
        getLink(next[b'child'], i, nodes, spaces, path);


resp = cjdns.NodeStore_nodeForAddr(0);
myIp6 = PublicToIp6_convert(resp[b'result'][b'key'])
getNode({b'child':myIp6.encode(),b'cannonicalLabel':b''}, b'', [], '', b'0000.0000.0000.0001')
