package LATMOS::Accounts::Utils;
use 5.010000;
use strict;
use warnings;
use Exporter ();
use vars qw(@ISA @EXPORT_OK @EXPORT);
use utf8;
use LATMOS::Accounts::Log;
use File::Temp qw(tempfile);

our $VERSION = (q$Rev$ =~ /^Rev: (\d+) /)[0];

@ISA = qw(Exporter);
@EXPORT = qw(to_ascii exec_command);
@EXPORT_OK = qw(to_ascii exec_command);

sub to_ascii {
    my ($text) = @_;
    return $text unless(defined($text));
    utf8::decode($text) unless(utf8::is_utf8($text));
    $text =~ s/œ/oe/g;
    $text =~ s/æ/ae/g;
    $text =~ tr/uàâäÂÄÀçéèêëÉÈÊËïîÏÎöôÖÔüûÛÜ/uaaaAAAceeeeEEEEiiIIooOOuuUU/;
    $text =~ s/([^[:ascii:]])//;
    $text
} 

sub exec_command {
    my ($command, $env) = @_;

    my @exec = ref $command
        ? (@$command)
        : ($command);
    la_log(LA_DEBUG, 'running command `%s\'', join(' ', @exec));

    my $pid = fork;
    if (!defined($pid)) {
        la_log(LA_ERR, "Can't launch script: cannot fork");
    } elsif ($pid) {
        # Father
        waitpid($pid, 0);
        if (my $exitstatus = $?) {
            la_log(LA_ERR, 'command %s exit with status %d',
                join(' ', @exec), $exitstatus);
        }
    } else {
        # Child
        foreach (keys %{ $env || {} }) {
            $ENV{"LA_$_"} = $env->{$_};
        }
        exec(@exec);
        exit($!);
    }
    1
}

sub parse_obj_file {
    my ($handle) = @_;

    my %attributes;
    while (my $line = <$handle>) {
        $line =~ /^#/ and next;
        chomp($line);
        my ($attr, $value) = $line =~ /^\s*(\S+):\s*(.*)\s*$/ or
            die "Malformed input file\n";
        $value =~ s/\s*$//;
        $value =~ s/\\n/\n/g;
        if ($attributes{$attr}) {
            if (ref $attributes{$attr}) {
                push(@{ $attributes{$attr} }, $value);
            } else {
                my $temp = $attributes{$attr};
                $attributes{$attr} = [ $temp, $value ];
            }
        } else {
            $attributes{$attr} = $value;
        }
    }
    %attributes
}

sub dump_read_temp_file {
    my ($writecb, $readcb) = @_;

    my ($fh, $filename) = tempfile(CLEANUP => 0);
    $writecb->($fh) or return;
    $fh = undef; # closing file
    my $res;
    
    my @stat = stat($filename);
    while (1) {
        my $cmd = ($ENV{EDITOR} || 'vi') . " $filename";
        warn "Running $cmd\n";
        if (system($cmd) == -1 ) {
            warn "Cannot run editor $!\n";
            last;
        }
        if ((stat($filename))[9] == $stat[9]) {
            warn "No change existing\n";
            last;
        }

        open($fh, '<', $filename) or return;
        $res = $readcb->($fh);
        $fh = undef; # closing again
        $res < 2 and last;
    }
    unlink($filename);
    $res;
}

1;
