package Common::Sys::File;

use strict;
use warnings;

use File::Stat;
use Math::Round;
use File::Basename(qw/dirname basename/);

use base 'Class::Accessor';

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

__PACKAGE__->mk_accessors(qw/path parent name daysold stat size title type compress_exec/);

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

sub _init {
    my $self = shift;
    my $path = shift || $self->path;

    $self->path($path);
    $self->stat( File::Stat->new($path) );
    $self->size( -s $path );
    $self->parent( dirname($path) );
    $self->name( basename($path) );

    my ( $title, $ext ) = $self->name =~ m/(.*)(\..*)$/;
    $self->title($title);
    $self->type($ext);

    my $daysold = round( ( time - $self->stat->mtime ) / 86400 );
    $self->daysold($daysold);

    $self;

}

sub exists {
    my $self = shift;
    -e $self->path;
}

sub _compress {
    my $self = shift;
    my $out  = runlogcmd( $self->compress_exec . ' ' . $self->path );
    my $file;
    if ( $out->[2] ) {
        logMessage( 'error', $out->[1] );
    } else {
        my $path    = $self->parent . '/' . $self->title;
        my $ls      = runcmd("ls $path* | tr -d '\n'");
        my $newpath = $ls->[0];
        $self->_init($newpath);
    }
    $file;
}

sub compress {
    my $self = shift;
    $self->compress_exec('sudo /usr/bin/pigz --force --fast');
    $self->_compress();
}

sub uncompress {
    my $self = shift;
    $self->compress_exec('sudo /usr/bin/unpigz --force --fast');
    $self->_compress();
}

1;
