#!/usr/bin/env perl

use strict;
use warnings;

use SQL::Translator;

package SchemaDiag::Args {
  use Moose;
  with 'MooseX::Getopt';

  use Module::Runtime qw/use_module/;

  has schema => (is => 'ro', isa => 'Str', required => 1, documentation => 'The name of the schema class to load. Must be a DBIx::Class');
  has _schema => (
    is => 'ro',
    lazy => 1,
    default => sub {
      my $self = shift;
      my $schema_name = $self->schema;
      $self->use_lib_include_dir;
      use_module $schema_name;
      my $schema = $schema_name->admin_connection;
      return $schema;
    }
  );
  has file => (is => 'ro', isa => 'Str', lazy => 1, default => sub {
      my $self = shift;
      return sprintf("%s_schema.png", $self->schema);
    },
    documentation => 'The file to output the schema diagram to'
  );
  has width => (is => 'ro', isa => 'Int', default => 1000, documentation => 'The width of the image');
  has height => (is => 'ro', isa => 'Int', default => 600, required => 1, documentation => 'The height of the image');

  has include_dir => (
    traits => ['Getopt'],
    is => 'ro',
    isa => 'Str',
    default => 'lib',
    cmd_aliases => 'I',
    documentation => 'library directory for the schema (will be added to @INC). Defaults to lib',
  );

  sub use_lib_include_dir {
    my $self = shift;
    require lib;
    lib->import($self->include_dir);
  }

}

my $opts = SchemaDiag::Args->new_with_options;

SQL::Translator->new(
    parser => 'SQL::Translator::Parser::DBIx::Class',
    parser_args => { dbic_schema => $opts->_schema },
    to => 'GraphViz',
    producer_args => {
      out_file => $opts->file,
      layout => 'sfdp',
      overlap => 'false',
      node => { shape => 'record' },
      show_datatypes => 1,
      friendly_ints => 1,
      friendly_ints_extended => 1,
      show_sizes => 1,
      show_constraints => 1,
      show_indexes => 1,
      width => $opts->width,
      height => $opts->height,
    },
)->translate;

