package CLMApp::Controller::Root;
use Mojo::Base 'Mojolicious::Controller';
use Data::Show;
use LWP::UserAgent::JSON;
use HTTP::Request::JSON;
use File::Stat;
use Cwd;


# sub listmodule{
# 	my $c = shift;

# 	$c->render(template => 'views/list');
# }


sub dashboard {
	my $c = shift;

	 my $customercnt = $c->db->resultset('Customer')->search(undef)->count;
	 my $customeractivecnt = $c->db->resultset('Customer')->search({statusid=>1})->count;
	 my $customerinactivecnt = $c->db->resultset('Customer')->search({statusid=>2})->count;
	 $customercnt =~ s/(\d)(?=(\d{3})+(\D|$))/$1\,/g;	 
	 $customeractivecnt =~ s/(\d)(?=(\d{3})+(\D|$))/$1\,/g;
	 $customerinactivecnt =~ s/(\d)(?=(\d{3})+(\D|$))/$1\,/g;
	 my $chaingrpcnt = $c->db->resultset('ChainGroup')->search(undef)->count;
	 my $dcompanycnt = $c->db->resultset('DistributorCompany')->search(undef)->count;

	my $dir = '/home/sites/clm.dmadelivers.com/www/files/opf/';
	opendir(my $dh, $dir);
	chdir($dir);
	my @files = sort { (stat($a))[10] <=> (stat($b))[10] } (readdir($dh));
	closedir($dh);
	my @opffiles;
	foreach my $f (@files){
		push(@opffiles, $f) if $f =~ /DMAOPF\d+\.TXT$/;
	}

	my @opftable;
	my $n = 10;
	my @opff = ($n >= @opffiles) ? @opffiles : @opffiles[-$n..-1];
	# show @opff;
	foreach my $opf (@opff){
		my $ostat = new File::Stat($dir . $opf);
		my $o = {
			file => $opf,
			mtime => $ostat->mtime,
			size => $ostat->size,
		};
		$c->readfile($dir . $opf,$o);
		push(@opftable, $o);
	}

	  my $cwd = getcwd();
	  my @hg = `cd $cwd; /usr/bin/hg tip`;
	  my $tip;
	  foreach my $h (@hg){
	    # show $h;
	    if($h =~ /changeset:\s+(.*)/i){
	      $tip = $1;
	    }
	  }

	  # show $tip;

show @opftable;

	$c->stash(module => 'dashboard', customercnt => $customercnt, chaingrpcnt => $chaingrpcnt, dcompanycnt => $dcompanycnt, customeractivecnt => $customeractivecnt, customerinactivecnt => $customerinactivecnt, hgtip => $tip);
	$c->render(template => 'root/dashboard');
}

sub opfftp{
	my $c = shift;
	my $f = $c->stash('file') || $c->req->param('file');
	my $msg = 'FTP Upload Starting... Please Wait...';

	my $url = 'http://' . $c->req->url->base->host . '/opfftpupload/' . $f;
	$c->stash(url => $url, msg => $msg);
	$c->render(template => 'root/redirect');
}

sub opfftpupload{
	my $c = shift;
	my $f = $c->stash('file') || $c->req->param('file');

	$c->render_later;


	# show $url;
	my $cmd = '/usr/bin/perl /home/sites/clm.dmadelivers.com/www/clmapp/lib/script/ftp.opf.pl ' . $f . ' 2>&1';
	my @res = `$cmd`;	
show @res;
	$c->stash('ftpresult', join("", @res));
	$c->opf;
}

sub opfdownload{

	my $c = shift;
	my $f = $c->stash('file') || $c->req->param('file');

show $f;

    $c->render_file(filepath => '/home/sites/clm.dmadelivers.com/www/clmapp/public/files/opf/' . $f, 'filename' => $f );


}


sub opf{

	my $c = shift;

	my $dir = '/home/sites/clm.dmadelivers.com/www/clmapp/public/files/opf/';
	opendir(my $dh, $dir);
	chdir($dir);
	my @files = sort { (stat($a))[10] <=> (stat($b))[10] } (readdir($dh));
	closedir($dh);
	my @opffiles;
	foreach my $f (@files){
		push(@opffiles, $f) if $f =~ /DMAOPF\d+\.TXT$/;
	}

	my @opftable;
	my $n = 10;
	my @opff = ($n >= @opffiles) ? @opffiles : @opffiles[-$n..-1];
	# show @opff;
	foreach my $opf (@opff){
		my $ostat = new File::Stat($dir . $opf);
		my $o = {
			file => $opf,
			mtime => $ostat->mtime,
			size => $ostat->size,
		};
		$c->readfile($dir . $opf,$o);
		push(@opftable, $o);
	}

	@opftable = sort { $b->{mtime} <=> $a->{mtime} } @opftable;

	$c->stash('ftpresult',undef) unless $c->stash('ftpresult');
	$c->stash(module => 'opfftp', opftable => \@opftable );
	$c->render(template => 'root/opf');


}

sub opfreturnfile{
	my $c = shift;

	$c->render_later;
	my $subprocess = Mojo::IOLoop::Subprocess->new;
	my $res;
	$subprocess->run(
	  sub {
	    my $subprocess = shift;
	    my $res = `/usr/bin/perl /home/sites/clm.dmadelivers.com/clmapp/lib/script/ftp.download.pl`;

	    return $res;
	  },
	  sub {
	    my ($subprocess, $err, @results) = @_;
	    $c->render(text => 'OPF Return File: ' . join("\n", @results));
	    # $c->render(text => 'UploadPresale.txt Sent to AWS S3 dma-uploads/dma-uploads/');
	  }
	);	

}


sub readfile{
	my $c = shift;
	my $file = shift;
	my $spec = shift;


	my $csv = Text::CSV->new ( { binary => 1, sep_char => "\t", } ) or die "Cannot use CSV: ".Text::CSV->error_diag ();
	open my $fh, "<:encoding(utf8)", $file or die "test.csv: $!";
	my @rows;
	my $active; my $system;
	while ( my $row = $csv->getline( $fh ) ) {
		$spec->{active}++ if $row->[11] == 1;
		$spec->{inactive}++ if $row->[11] == 2;
		$spec->{systemcnt}++ if $row->[24] ne "";
#		$spec->{bpcnt}++ if $row->[25] == 1;
		$spec->{rowcnt}++;
	}


}


sub sessionjson{
	my $c = shift;
	my $session = $c->session;
	$c->render(json => $session);
}

sub gps{

	my $c = shift;
	my $input = $c->req->param('input'); # places
	my $address = $c->req->param('address'); # geocode
	my $place_id = $c->req->param('place_id'); # geocode

	my $url = $input ? "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=$input&key=AIzaSyCP1YIwEFWU7WDiNbUdo4MPbOZEJcQtN9I" : "https://maps.googleapis.com/maps/api/geocode/json?place_id=$place_id&key=AIzaSyCP1YIwEFWU7WDiNbUdo4MPbOZEJcQtN9I";
	show $url;
	my $ua = LWP::UserAgent::JSON->new;
	my $req = HTTP::Request::JSON->new(GET => $url);
	my $response = $ua->request($req);
	my $json = $response->json_content;
	show $json;
	$c->render(json => $json);

}


1;
