package Daje::Plugin::Perl::Generate::Methods;
use Mojo::Base 'Daje::Plugin::Perl::Base::Common', -base, -signatures;

our $VERSION = '0.01';

has 'fields';
has 'pkey' ;
has 'fkey' ;
has 'insert' ;
has 'update' ;
has 'select_fields' ;
has 'select_method' ;

sub generate($self) {
    $self->pkey($self->_get_from_pkey());
    $self->fkey($self->_get_from_fkey());
    $self->insert($self->_insert_method());
    $self->update($self->_update_method());
    $self->select_fields($self->_select_fields());
    $self->select_method($self->_select_method());
}

sub _select_method($self) {
    my $tpl = $self->template->get_data_section('load_list');

    return $tpl;
}

sub _select_fields($self) {
    my $tpl = $self->template->get_data_section('fields_method');
    my $select = $self->fields->select();
    my $p_key = $self->fields->primary_key();
    my $table_name = $self->json->{table_name};

    $tpl =~ s/<<select_fields>>/$select/ig;
    $tpl =~ s/<<primary_key>>/$p_key/ig;
    $tpl =~ s/<<table_name>>/$table_name/ig;
    return $tpl;
}

sub _update_method($self) {
    my $tpl = $self->template->get_data_section('update_data');
    my $table_name = $self->json->{table_name};
    $tpl =~ s/<<table_name>>/$table_name/ig;
    return $tpl;
}

sub _insert_method($self) {
    my $tpl = $self->template->get_data_section('insert_data');
    my $table_name = $self->json->{table_name};
    $tpl =~ s/<<table_name>>/$table_name/ig;
    return $tpl;
}

sub _get_from_fkey($self) {
    my $load_from_fkey = "";
    my $f_key = $self->fields->foreign_keys();
    my $table_name = $self->json->{table_name};
    my $select = $self->fields->select();
    if (defined $f_key) {
        my $length = scalar @{$f_key};
        for (my $i = 0; $i < $length; $i++) {
            my $tpl = $self->template->get_data_section('load_from_fkey');
            $tpl =~ s/<<foreign_key>>/@{$f_key}[$i]/ig;
            $tpl =~ s/<<table_name>>/$table_name/ig;
            $tpl =~ s/<<select_fields>>/$select/ig;
            $load_from_fkey .= $tpl . "\n\n";
        }
    }
    return $load_from_fkey;
}

sub _get_from_pkey($self){
    my $load_from_pkey = $self->template->get_data_section('load_from_pkey');
    my $p_key = $self->fields->primary_key();
    my $select = $self->fields->select();

    my $table_name = $self->json->{table_name};
    $load_from_pkey =~ s/<<primary_key>>/$p_key/ig;
    $load_from_pkey =~ s/<<table_name>>/$table_name/ig;
    $load_from_pkey =~ s/<<select_fields>>/$select/ig;
    return $load_from_pkey;
}
1;
#################### pod generated by Pod::Autopod - keep this line to make pod updates possible ####################

=head1 NAME

Daje::Plugin::Perl::Generate::Methods


=head1 REQUIRES

L<Mojo::Base> 


=head1 METHODS

=head2 generate($self)

 generate($self)();


=cut

