#!python
#
# Generate a graph and dump in standard output.
# Copyright (c) 2019, Hiroyuki Ohsaki.
# All rights reserved.
#
# $Id: $
#

# This program is free software: you can redistribute it 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
# 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/>.

# This program is contributed by Hal.

import os
import random
import sys

from perlcompat import die, getopts
import graph_tools

def usage():
    prog = os.path.basename(sys.argv[0])
    types = '/'.join(graph_tools.CREATE_TYPES)
    export_fmts = '/'.join(graph_tools.EXPORT_FORMATS)
    die(f"""\
usage: {prog} [-du] [-t type] [-s seed] [-o format] params...
  -d         generate directed graph (default)
  -u         generate undirected graph
  -t type    specify graph type ({types})
             (parameters) random/random_sparse: N E [no_multiedge]
                          barabasi/ba: N m0 m
                          barandom: N E m0
  			  general_ba: N m0 m gamma
                          ring: N step
                          tree: N
			  btree:
			  latent: N E error_ratio 
                                  [confer abs/binary/linear/sigmoid] 
				  [dist uniform/normal/exponential]
			  treeba: N alpha
			  lattice: dim n [is_torus]
			  voronoi: n width height
                          degree_bounded/db: N E
                          configuration [degree_seq]
                          li_maini: T M m0 m alpha n
  -s seed    specify random number seed
  -o format  output graph format ({export_fmts})
""")

def validate_params(alist):
    params = []
    for param in alist:
        try:
            cls = type(eval(param))
            if cls == int:
                param = int(param)
            elif cls == float:
                param = float(param)
            elif cls == bool:
                param = True if param == 'True' else False
            else:
                param = map(int, param.split(','))
                param = list(param)
        except:
            pass
        params.append(param)
    return params

def main():
    opt = getopts('dut:s:o:') or usage()
    directed = opt.d if opt.d else not opt.u
    atype = opt.t if opt.t else 'random'
    seed = opt.s
    out_format = opt.o if opt.o else 'dot'

    if seed:
        random.seed(seed)
    g = graph_tools.Graph(directed)
    g = g.create_graph(atype, *validate_params(sys.argv[1:]))
    print(g.export_graph(out_format))

if __name__ == "__main__":
    main()
