package Stats::Redshift;

use strict;
use warnings;

use lib '/app/tools/common/lib';
use Common::Session;

use base 'Class::Accessor';

__PACKAGE__->mk_accessors(qw/type redshift_schema/);

sub new {
    my $class = shift;
    my $self  = { 'type' => shift };
    bless $self, $class;
    $self->_init();
    $self;
}

sub _init {
    my $self = shift;
    if ( $self->type ne 'rps' and $self->type ne 'dtmv' ) {
        logMessage( 'fatal', __PACKAGE__ . '::new requires types for rps & dtmv not ' . $self->type );
        exit 1;
    }
    $self->redshift_schema( 'royshare.' . $self->type );
}

sub dosql {
    my $self  = shift;
    my $sql   = shift;
    my $rsdbh = Common::Session::getdbh('redshift');
    eval {
        local $SIG{__WARN__} = sub {
            my $warn = shift;
            $warn =~ m/.*?:\s+(.*)\n/;
            logMessage( 'info2', $1 );
        };
        my $sth = $rsdbh->prepare($sql);
        $sth->execute();

        my $rowcnt;
        if ( $sth->rows and $sth->rows > 0 ) {
            $rowcnt = $sth->rows;
        } elsif ( $sth->rows and $sth->rows < -1 ) {
            ## amount of rows is too large for $sth->rows
            ## calc rowcount using 2^32
            $rowcnt = 2**32 + $sth->rows;
        }
        if ( defined $rowcnt ) {
            if ( $sql =~ m/delete/i ) {
                logMessage( 'warn2', $rowcnt . " rows removed" );
            } elsif ( $sql =~ m/insert/i ) {
                logMessage( 'info2', $rowcnt . " rows created" );
            } else {
                logMessage( 'info2', $rowcnt . " rows processed" );
            }
        }
    };
    if ( $@ or ( defined $rsdbh and $rsdbh->err ) ) {
        logMessage( 'error2', "$@ - " . ( defined $rsdbh ? $rsdbh->errstr : '' ) );
        return 1;
    }
    return 0;
}

sub truncate {
    my $self   = shift;
    my $table  = shift;
    my $schema = $self->redshift_schema;

    $table = "${schema}.${table}";

    logMessage( 'warn2', "Truncating table $table" );

    # $self->dosql("TRUNCATE TABLE $table");
    $self->dosql("DELETE FROM $table");

}

1;
