package LATMOS::Accounts::Synchro;

use 5.010000;
use strict;
use warnings;
use base qw(Config::IniFiles);
use LATMOS::Accounts::Bases;
use LATMOS::Accounts::Log;
use LATMOS::Accounts::Utils qw(exec_command);

=head1 NAME

LATMOS::Accounts::Synchro - Perl extension for blah blah blah

=head1 SYNOPSIS

  use LATMOS::Accounts;
  blah blah blah

=head1 DESCRIPTION

Stub documentation for LATMOS::Accounts, created by h2xs. It looks like the
author of the extension was negligent enough to leave the stub
unedited.

Blah blah blah.

=head1 FUNCTIONS

=cut

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

=head2 new($from, $to, %options)

Create a new synchronisation where $from and $to are LATMOS::Accounts::Base
based objects. $to can be an array ref of objects.

=cut

sub new {
    my ($class, $from, $to, %options) = @_;

    if ($options{state_file} && ! -w $options{state_file}) {
        # don't exists, we have to create it
        open(my $handle, '>', $options{state_file}) or do {
            la_log(LA_ERR, "Cannot open status file %s", $options{state_file});
            return;
        };
        print $handle "[_default_]\n";
        close($handle);
    }

    my $self = Config::IniFiles->new(
        $options{state_file}
        ? (-file => $options{state_file})
        : (),
    );

    if ($options{state_file} && !$self->GetFileName) {
        $self->SetFileName($options{state_file});
    }
    
    $self->{from} = $from or do {
        la_log(LA_ERR, "No database source");
        return;
    };
    $self->{options} = { %options };

    # allow ref and array ref of, eg
    # to = $foo and $to = [ $foo, $bar ]
    foreach (ref($to) eq 'ARRAY' ? @{ $to || []} : ($to)) {
        push(@{$self->{to}}, $_);
    }
    bless($self, $class)
}

sub name {
    $_[0]->{options}{name}
}

sub from {
    my ($self) = @_;
    return $self->{from}
}

sub to {
    my ($self) = @_;
    return @{$self->{to} || []};
}

=head2 load_dest

Try to loaded all base, return the count of filtrered base which cannot
be loaded

=cut

sub load_dest {
    my ($self) = @_;
    my @loaded;
    my $unloaded = 0;
    foreach ($self->to) {
        if($_->load) {
            push(@loaded, $_);
        } else {
            $unloaded++;
        }
    }
    $self->{to} = \@loaded;
    return $unloaded;
}

sub _traverse {
    my ($self, $callback) = @_;
    
    # listing existing obj one time:
    foreach my $otype ($self->from->list_supported_objects) {
        
        # If no dest support $otype, we skip
        my @obj_dest_base = grep {
            $_->is_supported_object($otype)
        } $self->to or next;

        # loading object list one time for all
        # TODO optimize this, using rev of objects

        foreach my $destbase (@obj_dest_base) {
            $callback->($otype, $destbase);
        }
    }
}

sub _traverse_update {
    my ($self, %options) = @_;
    $self->_traverse(
        sub {
            my ($otype, $destbase) = @_;
            my @lobjfrom = $self->from->list_objects_from_rev(
                $otype,
                $self->val($self->from->label, $destbase->label),
            );
            my @common_fields = $options{attr_cb}->($self->from, $destbase, $otype) or return;
            my %exists = map { $_ => 1 } $destbase->list_objects($otype);
            foreach my $uid (@lobjfrom) {
                my $sobj = $self->from->get_object($otype, $uid);
                if (!$self->{options}{test}) {
                    my $res = $destbase->sync_object(
                        $sobj,
                        nocreate => ($self->{options}{nocreate} || $options{nocreate}),
                    );
                    if (defined $res) {
                        la_log(LA_INFO,
                            "%s::%s::%s => %s (%s)",
                            $self->from->label, $otype, $uid,
                            $destbase->label, $res
                        ) if ($res);
                    } else {
                        la_log(LA_ERR,
                            "Error syncing %s::%s::%s => %s",
                            $self->from->label, $otype, $uid, $destbase->label
                        ); 
                    }
                }
            }
        }
    );
}

sub _traverse_delete {
    my ($self, %options) = @_;
    $self->_traverse(
        sub {
            my ($otype, $destbase) = @_;
            my %exists = map { $_ => 1 } $destbase->list_objects($otype);
            my %srcexists = map { $_ => 1 } $self->from->list_objects($otype);
            foreach (keys %exists) {
                if (!$srcexists{$_}) {
                    if ($destbase->delete_object($otype, $_)) {
                        print "delete " . $destbase->label . '::' . $otype . '::' . "$_\n";
                    } else {
                        la_log(LA_ERR, "cannot delete " . $destbase->label . '::' . $otype . '::' . "$_");
                    }
                }
            }
        }
    );
}

sub enter_synch_mode {
    my ($self) = @_;
    my %state = ();
    $state{$self->from->label} = $self->from->wexported(0);
    foreach ($self->to) {
        $state{$_->label} = $_->wexported(1);
    }
    la_log(LA_DEBUG, "Entering synch mode, old state: %s", join(', ', map {
            "$_ => $state{$_}" } sort keys %state));
    %state
}

sub leave_synch_mode {
    my ($self, %state) = @_;
    la_log(LA_DEBUG, "Leaving synch mode");
    $self->from->wexported($state{$self->from->label});
    foreach ($self->to) {
        $_->wexported($state{$_->label});
    }
}

sub sync_object {
    my ($self, $otype, $uid) = @_;
    my %state = $self->enter_synch_mode;
    if (my $sobj = $self->from->get_object($otype, $uid)) {
        foreach ($self->to) {
            if (my $res = $_->sync_object($sobj)) {
                la_log(LA_INFO, $_->label . " $uid ($otype) $res");
            } else {
                la_log(LA_ERR, "error synching $uid ($otype) to " . $_->label);
            }
        }
    } else {
        foreach ($self->to) {
            if ($_->get_object($otype, $uid)) {
                $_->get_object($otype, $uid) or do {
                    la_log("Cannot sync (delete) %s %s");
                }
            }
        }
    }
    foreach ($self->to) {
        $_->commit;
    }

    $self->run_post_synchro;

    $self->leave_synch_mode(%state);

    1;
}

sub process {
    my ($self) = @_;

    $self->from->load or return;
    # if any cannot be loaded, return,
    # TODO we need a way to force if some still can be sync
    $self->load_dest and return;
    
    my %state = $self->enter_synch_mode;

    # tracking current base revision:
    $self->{current_rev} = $self->from->current_rev;

    my %delayed;
    $self->_traverse_delete;
    $self->_traverse_update(
        attr_cb => sub {
            my ($from, $to, $otype) = @_;
            my %fields = ();
            my %delayed = map { $_ => 1 } $to->delayed_fields($otype);
            foreach ($from->list_canonical_fields($otype, 'r')) {
                $delayed{$_} and next;
                $fields{$_} ||= 0; # avoid 
                $fields{$_}++;
            }
            foreach ($to->list_canonical_fields($otype, 'w')) {
                $delayed{$_} and next;
                $fields{$_} ||= 0; # avoid 
                $fields{$_}++;
            }
            # field having value are in both
            grep { $fields{$_} == 2 } keys %fields;
        },
    );
    $self->_traverse_update(
        attr_cb => sub {
            my ($from, $to, $otype) = @_;
            my %fields = ();
            my %delayed = map { $_ => 1 } $to->delayed_fields($otype);
            foreach ($from->list_canonical_fields($otype, 'r')) {
                $delayed{$_} or next;
                $fields{$_} ||= 0; # avoid 
                $fields{$_}++;
            }
            foreach ($to->list_canonical_fields($otype, 'w')) {
                $delayed{$_} or next;
                $fields{$_} ||= 0; # avoid 
                $fields{$_}++;
            }
            # field having value are in both
            grep { $fields{$_} == 2 } keys %fields;
        },
        nocreate => 1,
    ) unless($self->{options}{nocreate} || $self->{options}{test});

    foreach ($self->to) {
	la_log(LA_DEBUG, "Calling commit on %s", $_->label);
        $_->commit or next;
        $self->newval($self->from->label, $_->label, $self->{current_rev}) if($self->{current_rev});
    }

    $self->run_post_synchro;

    $self->RewriteConfig
        if($self->GetFileName && !($self->{options}{nocreate} || $self->{options}{test}));
    
    $self->leave_synch_mode(%state);

    1;
}

sub run_post_synchro {
    my ($self) = @_;

    $self->{options}{post} or return 1;

    la_log(LA_INFO, "Running post synchro `%s'", $self->{options}{post});

    exec_command($self->{options}{post}, $self->{options});
}


1;

__END__
# Below is stub documentation for your module. You'd better edit it!

=head1 SEE ALSO

Mention other useful documentation such as the documentation of
related modules or operating system documentation (such as man pages
in UNIX), or any relevant external documentation such as RFCs or
standards.

If you have a mailing list set up for your module, mention it here.

If you have a web site set up for your module, mention it here.

=head1 AUTHOR

Thauvin Olivier, E<lt>olivier.thauvin@latmosipsl.frE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2009 by Thauvin Olivier

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.10.0 or,
at your option, any later version of Perl 5 you may have available.


=cut
