package Platform;
use strict;
use warnings;
use DateTime;

use Apache2::ServerUtil;
use Template;

use Platform::Email;
use Platform::Session;
use Platform::Account;
use Platform::Event;
use Platform::Attendee;
use Platform::Edit_Profile_Request;

use HTML::Mason::Escapes;

sub configure :method {
  my $class = shift;
  $HTML::Mason::Commands::CONFIG
    = $Platform::CONFIG
      = YAML::XS::LoadFile(shift);

  Platform::DBI->connection( @{$Platform::CONFIG->{common}{database}});


}

# Return an absolute path given a config key to a relative one
sub path_from_config {
  my ($config_key) = @_;
  my $path = $Platform::CONFIG;

  foreach my $key (split(/\./, $config_key)) {
    $path = $path->{$key};
  }

  my $server_root = $ENV{'SERVER_ROOT'};
  unless ($server_root) {
    $server_root = Apache2::ServerUtil::server_root();
  }

  return join('/', $server_root, $path);
}


sub html_entities_escape
{
    return unless defined ${ $_[0] };

    # HTML::Entities isn't compatible with UTF-8, but works with at least the 
    # single byte Unicode characters we have so far.
    utf8::is_utf8(${ $_[0] }) || utf8::decode(${ $_[0] });

    HTML::Entities::encode_entities( ${ $_[0] } );
}


sub highlight {
  return unless defined ${ $_[0] };

  ${ $_[0] } =~ s#\*([^*]+)\*#<span class="highlight">$1</span>#g;
}

sub convert_timezone {
  my ($class, $date, $format) = @_;
  return '' unless $date;

  my $timezone = $Platform::CONFIG->{common}{time_zone};

  $timezone = 'America/New_York' unless $timezone;
  $format = '%m/%d/%Y' unless $format;

  my $date2 = DateTime->new(
    year      => $date->year,
    month     => $date->month,
    day       => $date->day,
    hour      => $date->hour,
    minute    => $date->minute,
    second    => $date->second,
    time_zone => 'UTC'
  );

  $date2->set_time_zone($timezone);
  return $date2->strftime($format);
}

1;
