##########################################################################
# This file is part of Vacuum Magic
# Copyright (C) 2008 by UPi <upi at sourceforge.net>
##########################################################################

use strict;

##########################################################################
# CONFIG SAVE/LOAD
##########################################################################

sub GetConfigVars {
  my ($i, $j);
  my @result = qw(PhysicalScreenWidth PhysicalScreenHeight TutorialPlayed NumGuys DifficultySetting MusicEnabled SoundEnabled FullScreen FpsIndicator TimePrecisePlayback MovieMode Cheat Language);
  for ($i=0; $i < scalar @Players; ++$i) {
    for ($j=0; $j < 5; ++$j) {
      push @result, ("Players[$i]->{keys}->[$j]");
    }
  }
  return @result;
}

sub SaveConfig {
  my ($filename, $varname, $value);
  $filename = &GetConfigFilename();

  open CONFIG, "> $filename" or return;
  foreach $varname (&GetConfigVars) {
    eval("\$value = \$$varname"); die $@ if $@;
    print CONFIG "$varname = $value\n";
  }
  close CONFIG;
}

sub LoadConfig {
  my ($filename, $text, $varname);

  $text = '';
  $filename = &GetConfigFilename();
  if (open CONFIG, "$filename") {
    read CONFIG, $text, 16384;
    close CONFIG;
  }
  
  foreach $varname (&GetConfigVars) {
    my $pattern = $varname;
    $pattern =~ s/\[/\\[/g;
    if ($text =~ /$pattern = (.+?)$/m) {
      eval( "\$$varname = '$1'" );
    }
  }
}

sub GetConfigFilename {
  if ( &IsMicrosoftWindows() ) {
    if ($ENV{USERPROFILE}) {
      return "$ENV{USERPROFILE}\\vacuum.cfg";
    }
    return "$DataDir/vacuum.cfg";
  }
  if ($ENV{HOME}) {
    return "$ENV{HOME}/.vacuumrc";
  }
  if (-w $DataDir) {
    return "$DataDir/vacuum.cfg";
  }
  return "/tmp/vacuum.cfg";
}

sub GetSavedGameDirectory {
  my $result = &_GetSavedGameDirectory();
  unless (-d $result) {
    warn "Unable to create $result: $!"  unless mkdir($result);
  }
  return $result;
}

sub _GetSavedGameDirectory {
  if ( &IsMicrosoftWindows() ) {
    if ($ENV{USERPROFILE}) {
      return "$ENV{USERPROFILE}/vacuum";
    }
    return "$DataDir/saved";
  }
  if ($ENV{HOME}) {
    return "$ENV{HOME}/.vacuum";
  }
  if (-w $DataDir) {
    return "$DataDir/saved";
  }
  return "/tmp/vacuum";
}

1;
