package Daje::Workflow::Database::Model::Context;
use Mojo::Base -base, -signatures;

# NAME
# ====
#
# Daje::Workflow::Database::Model::Context
#
#
# REQUIRES
# ========
#
# Mojo::Base>
#
# METHODS
# =======
#
#  load_fk($self)
#
#  load_pk($self)
#
#  save($self, $context)
#
#
# 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>
#


has 'db';
has 'context_pkey';
has 'workflow_pkey';


sub load_pk($self) {
    my $context = $self->_load_pk();
    unless(defined $context) {
        $context->{context_pkey} = 0;
        $context->{workflow_fkey} = $self->workflow_pkey;
        my $context_pkey = $self->save($context);
        $self->context_pkey($context_pkey);
        $context = $self->_load_pk();
    }

    return $context;
}

sub _load_pk($self) {
    my $data = $self->db->select(
        'context', ['*'],
        {
            context_pkey => $self->context_pkey
        }
    );

    my $hash;
    $hash = $data->hash if $data->rows > 0;

    return $hash;
}

sub load_fk($self) {
    my $context = $self->_load_fk();
    unless(defined $context) {
        $context->{context_pkey} = 0;
        $context->{workflow_fkey} = $self->workflow_pkey;
        my $context_pkey = $self->save($context);
        $self->context_pkey($context_pkey);
        $context = $self->_load_pk();
    }

    return $context;
}

sub _load_fk($self) {
    my $data = $self->db->select(
        'context', ['*'],
        {
            workflow_fkey => $self->workflow_pkey
        }
    );

    my $hash;
    $hash = $data->hash if $data->rows > 0;

    return $hash;
}

sub save($self, $context) {

    if ($context->{context_pkey} > 0) {
        $self->db->update(
            'context',
            {
                %$context
            },
            {
                context_pkey => $context->{context_pkey}
            }
        )
    } else {
        delete %$context{contextr_pkey};
        $context->{context_pkey} = $self->db->insert(
            'context',
            {
                %$context
            },
            {
                returning => 'context_pkey'
            }
        )->hash->{context_pkey}
    }

    return $context->{context_pkey};
}

1;





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

=head1 NAME


Daje::Workflow::Database::Model::Context




=head1 REQUIRES


Mojo::Base>



=head1 METHODS


 load_fk($self)

 load_pk($self)

 save($self, $context)




=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

