package Forms::Sflang2_sqla;

use strict;
use warnings;

use Gtk2::Ex::DbLinker::Form;
use Gtk2::Ex::DbLinker::Datasheet;
use Gtk2::Ex::DbLinker::SqlADataManager;
use Data::Dumper;
use Forms::Dnav2;

sub new {
    my ( $class, $href ) = @_;

    my $self = {
        gladefolder => $$href{gladefolder},
        dbh         => $$href{dbh},
        countryid   => $$href{countryid},
    };

    $self->{log} = Log::Log4perl->get_logger(__PACKAGE__);
    $self->{dnav} = Forms::Dnav2->new( ismain => 0 );
    $self->{dnav}->connect_signal_for( "add",   \&on_add_clicked,    $self );
    $self->{dnav}->connect_signal_for( "del",   \&on_delete_clicked, $self );
    $self->{dnav}->connect_signal_for( "apply", \&on_apply_clicked,  $self );

    $self->{builder} = $self->{dnav}->get_builder;
    $self->{builder}->add_from_file( $self->{gladefolder} . "/sflang2.bld" );
    $self->{builder}->connect_signals($self);

    #inclusion of the subform in his navigation tool
    my $w   = $self->{builder}->get_object('sflang_window');
    my $ctr = $self->{builder}->get_object('vbox1');
    $self->{dnav}->reparent( $ctr, $w );

    my $dman = Gtk2::Ex::DbLinker::SqlADataManager->new(
        dbh => $self->{dbh},
        select_param =>
          { -from => "speaks", -where => { countryid => $self->{countryid} } },
    );

    $self->{sform} = Gtk2::Ex::DbLinker::Form->new(
        data_manager    => $dman,
        builder         => $self->{builder},
        auto_apply      => 0,
        rec_spinner     => $self->{dnav}->get_object('RecordSpinner'),
        status_label    => $self->{dnav}->get_object('lbl_RecordStatus'),
        rec_count_label => $self->{dnav}->get_object("lbl_recordCount"),
    );

    #die Dumper ($dman->get_field_names);

    my $combodata = Gtk2::Ex::DbLinker::SqlADataManager->new(
        dbh          => $self->{dbh},
        select_param => {
            -from     => "langues",
            -where    => { -bool => "1=1" },
            -order_by => [qw(+langue)]
        }
    );

    $self->{sform}->add_combo(
        data_manager => $combodata,
        id           => 'langid',
        builder      => $self->{builder},
    );
    my $list = Gtk2::Ex::DbLinker::SqlADataManager->new(
        dbh          => $self->{dbh},
        select_param => {
            -from  => "speaks",
            -where => {
                langid    => $self->{langid},
                countryid => { "!=" => $self->{countryid} }
            }
        }
    );

    $combodata = Gtk2::Ex::DbLinker::SqlADataManager->new(
        dbh          => $self->{dbh},
        select_param => {
            -from     => "countries",
            -where    => { -bool => "1=1" },
            -order_by => [qw(+country)]
        }
    );

    my $tree = Gtk2::TreeView->new();
    $self->{dnav}->set_dataref( $self->{sform} );

    $self->{sf_list} = Gtk2::Ex::DbLinker::Datasheet->new(
        treeview     => $tree,
        data_manager => $list,
        fields       => [
            { name => "langid", renderer => "hidden" },
            {
                name         => "countryid",
                renderer     => "combo",
                data_manager => $combodata,
                fieldnames   => [ "countryid", "country" ],
            }
        ],
    );

    $self->{sform}->add_childform( $self->{sf_list} );

    #set up the datasheet
    #
    $self->{sf_list}->{dnav} = Forms::Dnav2->new( ismain => 0 );
    $self->{sf_list}->{dnav}
      ->connect_signal_for( "add", \&on_add_lst_clicked, $self );
    $self->{sf_list}->{dnav}
      ->connect_signal_for( "apply", \&on_apply_lst_clicked, $self );
    $self->{sf_list}->{dnav}
      ->connect_signal_for( "del", \&on_delete_lst_clicked, $self );
    my $scroll = Gtk2::ScrolledWindow->new;
    $scroll->add($tree);
    $self->{sf_list}->{dnav}->add_ctrl($scroll);
    $self->{sf_list}->{dnav}->set_dataref( $self->{sf_list} );

    my $ctrl_from = $self->{sf_list}->{dnav}->get_object('vbox1_main');
    my $ctrl_to   = $self->{builder}->get_object('alignment1');
    Gtk2::Widget::reparent( $ctrl_from, $ctrl_to );

    bless $self, $class;

}

sub on_countryid_changed {
    my ( $self, $value ) = @_;
    $self->{log}->debug("sf_langues: countryid_changed $value");
    $self->{countryid} = $value;
    $self->{sform}
      ->get_data_manager->query( -where => { countryid => $value } );
    $self->{sform}->update;

    $value = $self->{sform}->get_widget_value("langid");
    $self->{log}->debug("sf_langues: langid changed $value");
    $self->{sf_list}->get_data_manager->query( -where =>
          { langid => $value, countryid => { '!=' => $self->{countryid} } } );
    $self->{sf_list}->update;
}

sub on_langid_changed {
    my ( $b, $self ) = @_;
    my $value = $self->{sform}->get_widget_value('langid');
    if ($value) {
        $self->{log}->debug("sf_langues: langid_changed $value");
        $self->{langid} = $value;
        $self->{sf_list}->get_data_manager->query( -where =>
              { langid => $value, countryid => { '!=' => $self->{countryid} } }
        );
        $self->{sf_list}->update;
    }
}

sub on_delete_clicked {
    my $b    = shift;
    my $self = shift;
    $self->{deleting} = 1;
    $self->{sform}->delete;
}

sub on_add_clicked {
    my $b    = shift;
    my $self = shift;
    $self->{sform}->insert;
    $self->{sform}->set_widget_value( "countryid", $self->{countryid} );

}

sub on_apply_clicked {
    my $b    = shift;
    my $self = shift;
    if ( $self->{deleting} ) {
        $self->{sform}->apply;
        $self->{deleting} = 0;
        return;
    }

    $self->{log}->debug( "sform_apply country : "
          . $self->{countryid}
          . " langue : "
          . $self->{langid} );
    my %h = ( countryid => $self->{countryid}, langid => $self->{langid} );

#since the only values displayed are primary keys values, they are not saved when calling
# DataManager->save
# They have to be pass as an argument
# And to prevent from save to being called a second time when Form->apply runs
# the pk names is passed as to apply
    $self->{sform}->get_data_manager->save(%h);
    my @pks = $self->{sform}->get_data_manager->get_primarykeys;

    #print Dumper $self->{sform}->get_data_manager->get_autoinc_primarykeys;
    #print Dumper @pks;

    $self->{sform}->apply( \@pks );
    $self->{sform}->get_data_manager->query(
        -where => { countryid => $self->{countryid} } );
    $self->{sform}->update;
}

sub on_add_lst_clicked {
    my ( $b, $self ) = @_;
    $self->{sf_list}
      ->insert( $self->{sf_list}->{colname_to_number}->{"langid"} =>
          $self->{sform}->get_widget_value("langid") );

}

sub on_apply_lst_clicked {
    my ( $b, $self ) = @_;
    $self->{log}->debug("apply lst");
    if ( $self->{lst_deleting} ) {
        $self->{sf_list}->apply;
        $self->{lst_deleting} = 0;
        return;
    }

    my $dman = $self->{sf_list}->get_data_manager;
    my %old  = (
        countryid => $dman->get_field('countryid'),
        langid    => $dman->get_field('langid')
    );

    my %h = (
        langid    => $self->{langid},
        countryid => $self->{sf_list}->get_column_value('countryid')
    );
    $self->{log}->debug( "old values", Dumper %old );
    $self->{log}->debug( "new values", Dumper %h );
    my @pks = $dman->get_primarykeys;

#a new row is created in Datasheet->apply  and the inserting flag is turn to 1 (not in Datasheet->insert)
#so to instert a new row: calls Datasheet->aplly before saving in the new row with SqlADM->save
#passing the pk names to apply excludes these from being saved here
#since they are saved with the hashref  pass to DM->save
    $self->{sf_list}->apply( \@pks );
 my $row = $self->{sf_list}->get_current_row;
    $self->{log}->debug("row pos from grid: ", $row);
 # set dman to this row before saving, since dman is now positionned on the last row
    $dman->set_row_pos($row);

    $dman->save(%h);

    # $self->{sf_list}->apply(\@pks);

}

sub on_delete_lst_clicked {
    my $b    = shift;
    my $self = shift;
    $self->{lst_deleting} = 1;
    $self->{sf_list}->delete;
}

1;
