use strict;
use Data::Dumper;
use Getopt::Long;    # http://search.cpan.org/~jv/Getopt-Long-2.38/lib/Getopt/Long.pm
use CSS;             # http://search.cpan.org/~iamcal/CSS-1.09/CSS.pm

my $help                 = undef;  # Help toggle.
my $argvStyleSheetPathes = undef;  # Pathes to the CSS files (as given by the command line).
my @styleSheetPathes     = ();     # List ot pathes to style sheets.
my @properties           = ();     # List of CSS properties.
my %uniqProperties       = ();     # This hash is used to keep only one occurrence of each property.
my @tab                  = ();

# Parsing the command line.
unless ( GetOptions ( 'help'          => \$help,
                      'stylesheets=s' => \$argvStyleSheetPathes))
{ print STDERR "ERROR: Invalid command line!\n"; exit 1; }

if (defined($help)) { help(); exit 0; }
unless (defined($argvStyleSheetPathes)) { print STDERR "ERROR: Missing mandatory option --stylesheets.\n"; exit 1; }
@styleSheetPathes = split (/;/, $argvStyleSheetPathes);

# Loading and parsing.
foreach my $styleSheetPath (@styleSheetPathes)
{
  my @entries = ();
  my $css     = CSS->new( { 'parser' => 'CSS::Parse::Heavy' } );

  $css->read_file($styleSheetPath);

  # Get all properties.
  @entries = @{$css->{'styles'}};
  foreach my $entry (@entries)
  {
    if (exists($entry->{'properties'}))
    {
      my @properties = @{$entry->{'properties'}};
      foreach my $property (@properties) { $uniqProperties{"'" . $property->{'property'} . "'"} = 1; }
    }

    # In case you want the selectors...
    # if (exists($entry->{'selectors'})) { my @selectors = @{$entry->{'selectors'}}; }
  }
}

# Now, let's create the JavaScript list of properties.
@tab = keys %uniqProperties;
print '# Total: ' . int(@tab) . "\n";
print 'var cssProperties = new array(' . join(',', @tab) . ');';

exit 0;


sub help
{
  print STDOUT "Usage: perl css2js.pl (--help | --stylesheets=<list of style sheets>)\n";
}
