#!/usr/bin/perl

use strict;
use warnings;

use File::Basename;
use WWW::Shopify::Common::DBIx;
use Module::Find;
use Data::Dumper;
use WWW::Shopify::Field::String;
use Cwd 'abs_path';
use File::Basename;

chdir abs_path(__FILE__) . "/..";

my @Classes;

BEGIN {
	@Classes = grep { $_ !~ m/DBIx/ && $_ !~ m/NestedItem/ && $_ !~ m/::Item/ } findallmod WWW::Shopify::Model;
	for (@Classes) { eval "require $_"; }
}

my $DBIx = new WWW::Shopify::Common::DBIx();

for (@Classes) {
	die unless $_ =~ m/WWW::Shopify::/;
	my $Path = $';
	$Path =~ s/::/\//g;
	$Path .= ".pm";

	# We want to add in a bunch of accessors for all top-level classes for the shop to make things easier.
	my $shopLine = "";
	if ($_ eq 'WWW::Shopify::Model::Shop') {
		foreach my $Class (@Classes) {
			next if int(split(/\:\:/, $Class)) != 4 || $Class eq "WWW::Shopify::Model::Shop";
			$shopLine .= "\n	__PACKAGE__->has_many(" . $Class->plural() . " => '" . WWW::Shopify::Common::DBIx::transform_package($Class) . "', 'shop_id');";
		}
	}

	my $File = "
#!/usr/bin/perl
# NOTE - THIS FILE GENERATED BY DBIxGenerate.pl.
# To regenerate this file, simply call the script, and it'll dump the DBIx files into the working directory.

=head1 NAME

" . WWW::Shopify::Common::DBIx::transform_package($_) . " - Database Object for $_.

=cut

=head1 NOTICE

This is a generated class, made by WWW::Shopify/Utils/DBIxGenerate.pl. Do not modify.

=cut

use strict;
use warnings;

" . $DBIx->generateDBIx($_) . $shopLine . "

1;";
	my $OutPath = "Model/DBIx/Schema/Result/$Path";
	print "Generating $OutPath... ";
	mkdir dirname($OutPath) unless -d dirname($OutPath);
	open(my $OUTFILE, ">$OutPath") or die $!;
	print $OUTFILE $File;
	close($OUTFILE);
	print "Done.\n";
}

for (keys(%{$DBIx->{intermediateClasses}})) {
	die $_ unless $_ =~ m/WWW::Shopify::/;
	my $Path = $';
	$Path =~ s/::/\//g;
	$Path .= ".pm";

	my $File = "
#!/usr/bin/perl
# NOTE - THIS FILE GENERATED BY DBIxGenerate.pl.
# To regenerate this file, simply call the script, and it'll dump the DBIx files into the working directory.

=head1 NAME

" . WWW::Shopify::Common::DBIx::transform_package($_) . " - Database Object for $_.

=cut

=head1 NOTICE

This is a generated class, made by WWW::Shopify/Utils/DBIxGenerate.pl. Do not modify.

=cut

use strict;
use warnings;

" . $DBIx->{intermediateClasses}->{$_} . "

1;";
	my $OutPath = "$Path";
	print "Generating $OutPath... ";
	mkdir dirname($OutPath) unless -d dirname($OutPath);
	open(my $OUTFILE, ">$OutPath") or die "$! for $OutPath";
	print $OUTFILE $File;
	close($OUTFILE);
	print "Done.\n";
}
