package Daje::Workflow::Activities::Save;
use Mojo::Base 'Daje::Workflow::Common::Activity::Base', -base, -signatures;
use v5.42;

# NAME
# ====
#
# Daje::Workflow::Activities::Save - It creates and manages database objects
#
# SYNOPSIS
# ========
#
#     use Daje::Workflow::Activities::Save
#
#     use Mojo::Loader qw(load_class);
#
#     Expected input from workflow
#
#     "activity_data": {
#         "class": "Model to use"
#     }
#
# DESCRIPTION
# ===========
#
# Daje::Workflow::Activities::Save just saves a record in a table
#
# LICENSE
# =======
#
# Copyright (C) janeskil1525.
#
# This library is free software; you can redistribute it and/or modify
# it under the same terms as Perl itself.
#
# AUTHOR
# ======
#
# janeskil1525 E<lt>janeskil1525@gmail.comE<gt>
#

use Data::Dumper;
use Mojo::Loader qw(load_class);

sub save ($self) {

    my $data = $self->context->{context}->{payload};
    my $class = $self->activity_data->{class};
    if (my $e = load_class $class) {
        $self->error->add_error($e);
        $self->error->add_error($class . " Not found ");
    }
    return 0 if $self->error->has_error();
    say "Class = " . $class;

    try {
        my $dbclass = $class->new(db => $self->db);
        say $dbclass->primary_key_name . " " . Dumper($data);
        if (exists $data->{$dbclass->primary_key_name} and $data->{$dbclass->primary_key_name} > 0) {
            $self->model->insert_history(
                "Update object " . Dumper($data), " $class->update", 1
            );

            my $result = $dbclass->update($data);
            if($result->{result} == 0) {
                $self->error->add_error($result->{error});
            }
        } else {
            $self->model->insert_history(
                "New object "  . Dumper($data), " $class->insert", 1
            );
            my $tools_object_index_pkey = $dbclass->insert($data);
        }
    } catch ($e) {
        $self->error->add_error($e);
    };

    return 1;
}

1;

#################### pod generated by Pod::Autopod - keep this line to make pod updates possible ####################

=head1 NAME


Daje::Workflow::Activities::Save - It creates and manages database objects



=head1 SYNOPSIS


    use Daje::Workflow::Activities::Save

    use Mojo::Loader qw(load_class);

    Expected input from workflow

    "activity_data": {
        "class": "Model to use",
        "update": "Method in model to use for update",
        "insert": "Method in model to use for insert"
    }



=head1 DESCRIPTION


Daje::Workflow::Activities::Save just saves a record in a table



=head1 REQUIRES

L<Mojo::Loader> 

L<Data::Dumper> 

L<v5.42> 

L<Mojo::Base> 


=head1 METHODS

=head2 save

 save();


=head1 AUTHOR


janeskil1525 E<lt>janeskil1525@gmail.comE<gt>



=head1 LICENSE


Copyright (C) janeskil1525.

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.



=cut

