#!/usr/bin/perl -w -T

# TODO rewrite/replace with new dynamic fields if needed.

# Library path
BEGIN
{
    use vars qw($location $script_name $script_location $utils $debugfile);
    use Zymonic::Utils qw(clean debug death_handler);
    $main::SIG{__DIE__} = \&death_handler;

}

use Zymonic::Config;
use Zymonic::Session;
use Zymonic::DB;
use Zymonic::Auth;

$debugfile = STDERR;

my $action = clean( $ARGV[0] ) or die "Need to specifiy 'create' or 'delete' as argument\n";
die "Need to specifiy 'create' or 'delete' as argument\n" if $action ne 'create' && $action ne 'delete';
my $user = clean( $ARGV[1] ) || '';
my $ip_address = clean( $ARGV[2] ) || clean( $ENV{REMOTE_ADDR} ) || '127.0.0.1';

my $protocol = ( ( defined( $ENV{HTTPS} ) and $ENV{HTTPS} eq 'on' ) ? 'https' : 'http' );

# Clean path
$ENV{PATH} = "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/sbin:/bin:/usr/bin:/sbin:/usr/sbin";

# Create a session (CGI only)
$ENV{SERVER_NAME} = clean( $ENV{SERVER_NAME}, "-_" );
my $session = Zymonic::Session->new(
    ip_address => $ip_address,
    protocol   => $protocol
);

my $system = $session->system_name( $ENV{SERVER_NAME}, "/etc/zymonic" );

my $config = Zymonic::Config->new(
    system_name => $system,
    config_dir  => "/etc/zymonic",
    ip_address  => $ip_address,
    protocol    => 'https'
);

$session->{config} = $config;

my $db = Zymonic::DB->new( config => $config );

$session->{DB} = $db;

my $auth = Zymonic::Auth->new(
    config      => $config,
    session     => $session,
    DB          => $db,
    credentials => '',
    ip_address  => $session->ip_address
);
$auth->user($user);
$auth->logged_in( $user ? 'Y' : '' );
$auth->initialise();

$session->{auth} = $auth;
$session->{user} = $user || '';

$session->cgi->param( 'ZZpagename', 't_007_page' );
my $actual_result = $session->view_control;
my $process_id    = $actual_result->{currentpage}->{location}->[0]->{block}->[1]->{t_007_process}->{process_id};

my @test_data_order = qw(t_007_people);

my $test_data = {
    t_007_people => {
        Derek => {
            id         => '',
            set_values => { t_007_person_name => '\'Derek\'', t_007_person_email => '\'derek@test.com\'' },

        },
        Rodney => {
            id         => '',
            set_values => { t_007_person_name => '\'Rodney\'', },

        },
        Anton2 => {
            id         => '',
            set_values => { t_007_person_name => '\'Anton\'', t_007_person_email => '\'anton@test.com\'' }

        },
        John => {
            id         => '',
            set_values => { t_007_person_name => '\'John\'', },

        },
        Paul => {
            id         => '',
            set_values => { t_007_person_name => '\'Paul\'', },

        },
        George => {
            id         => '',
            set_values => { t_007_person_name => '\'George\'', t_007_person_email => '\'george@test.com\'' },

        },
        Ringo => {
            id         => '',
            set_values => { t_007_person_name => '\'Ringo\'', },

        },
        Liam => {
            id         => '',
            set_values => { t_007_person_name => '\'Liam\'', },

        },
        Noel => {
            id         => '',
            set_values => { t_007_person_name => '\'Noel\'', },

        },
        Lenny => {
            id         => '',
            set_values => { t_007_person_name => '\'Lenny\'', },

        },
        Anthony => {
            id         => '',
            set_values => { t_007_person_name => '\'Anthony\'', },

        },
        Declan => {
            id         => '',
            set_values => { t_007_person_name => '\'Declan\'', t_007_person_email => '\'declan@test.com\'' },

        },
        Alan => {
            id         => '',
            set_values => { t_007_person_name => '\'Alan\'', },

        },
        Pierre => {
            id         => '',
            set_values => { t_007_person_name => '\'Pierre\'', },

        },
        Jean => {
            id         => '',
            set_values => { t_007_person_name => '\'Jean\'', },

        },
        Anton => {
            id         => '',
            set_values => { t_007_person_name => '\'Anton\'', },

        },
        Raul => {
            id         => '',
            set_values => { t_007_person_name => '\'Raul\'', t_007_person_email => '\'raul@test.com\'' },

        },
        Xabi => {
            id         => '',
            set_values => { t_007_person_name => '\'Xabi\'', },

        },
        Kaka => {
            id         => '',
            set_values => { t_007_person_name => '\'Kaka\'', },

        },
        Ronaldo => {
            id         => '',
            set_values => { t_007_person_name => '\'Ronaldo\'', t_007_person_email => '\'ronaldo@test.com\'' },

        },
        Lionel => {
            id         => '',
            set_values => { t_007_person_name => '\'Lionel\'', },
        },
    },
};

if ( $action eq 'create' )
{

    foreach my $key (@test_data_order)
    {
        my $data  = $test_data->{$key};
        my $table = Zymonic::Table->new(
            table  => $key,
            config => $config,
            auth   => $auth,
            db     => $db,
        );

        foreach my $name ( keys %$data )
        {

            # Get the new record placeholder and set their fields
            eval { $table->get_records( { records_per_page => 999 } ); }
              or do
            {
                my $exception = $@;
                if ( $exception
                    and !$exception->isa('Zymonic::Exception::Table::Get_Record') )
                {
                    ref $exception ? $exception->rethrow : die $exception;
                }
            };
            $table->setup_placeholder;
            my $new_rec = ( grep { $_->{id} eq $table->{placeholder_id} } @{ $table->{records} } )[0];

            # set any fields on it
            foreach my $set_key ( keys %{ $data->{$name}->{set_values} } )
            {
                ( grep { $_->field eq $set_key } @{ $new_rec->{fields} } )[0]
                  ->value( eval "$data->{$name}->{set_values}->{$set_key}" );
            }

            # set process id
            ( grep { $_->field eq 'parent_process_id' } @{ $new_rec->{fields} } )[0]->value($process_id);

            $table->before_add;
            $data->{$name}->{id} = $table->add_record;

            # set id on fields
            $new_rec->{id} = $data->{$name}->{id};
            $new_rec->{ $table->keyfield } = $data->{$name}->{id};
            ( grep { $_->field eq $table->keyfield } @{ $new_rec->{fields} } )[0]->value( $data->{$name}->{id} );

            $table->after_add( $data->{$name}->{id}, $process_id );
        }
    }
}

if ( $action eq 'delete' )
{
    foreach my $key (@test_data_order)
    {
        my $data  = $test_data->{$key};
        my $table = Zymonic::Table->new(
            table  => $key,
            config => $config,
            auth   => $auth,
            db     => $db,
        );

        foreach my $name ( keys %$data )
        {

            # lookup record id
            eval { $table->get_records( { records_per_page => 999 } ); }
              or do
            {
                my $exception = $@;
                if ( $exception
                    and !$exception->isa('Zymonic::Exception::Table::Get_Record') )
                {
                    ref $exception ? $exception->rethrow : die $exception;
                }
            };
            my $rec;
            my $search = $name;
            $search =~ s/(.*)\d/$1/;
            foreach my $record (
                grep {
                    grep { $_ && $_->{value} eq $search }
                      @{ $_->{fields} || [] }
                } @{ $table->{records} || [] }
              )
            {
                my $parent_process_field =
                  ( grep { $_ && $_->field && $_->field eq 'parent_process_id' } @{ $record->{fields} } )[0];
                my $deleted_field = ( grep { $_ && $_->field && $_->field eq 'deleted' } @{ $record->{fields} } )[0];

                if (   $parent_process_field
                    && $parent_process_field->{value}
                    && $parent_process_field->{value} eq $process_id
                    && $deleted_field
                    && ( !$deleted_field->{value} || $deleted_field->{value} ne 'Y' ) )
                {
                    $rec = $record;
                    last;
                }
            }
            if ($rec)
            {
                $table->before_delete;
                $table->delete_record( $rec->{id} );

                # check that record was deleted
                eval { $table->get_records( { records_per_page => 999 } ); }
                  or do
                {
                    my $exception = $@;
                    if ( $exception
                        and !$exception->isa('Zymonic::Exception::Table::Get_Record') )
                    {
                        ref $exception ? $exception->rethrow : die $exception;
                    }
                };
            }
        }
    }
}
