#!/usr/bin/perl -Ilibs

use strict;
use warnings;

package API::Dashboard;

use Moose;

use API::Controller;
extends 'API::Controller';

__PACKAGE__->meta->make_immutable;

###############################################################################

sub dashboardIndex {
    my $self = (shift)->new({'input' => shift || {}});

    $self->data->{'templates'} = [ "index.html" ];

    $self->data->{'dashboards'} = [qw/Warehouse CSB Sales SM Wholesale/];

    return $self->result;
}

###############################################################################

sub viewDashboard {
    my $self = (shift)->new({'input' => shift || {}});

    $self->data->{'templates'} = [ "viewDashboard.html" ];

    $self->data->{'dashboard'} = $self->input->{'dashboard'};

    return $self->result;
}

###############################################################################

sub runBatch {
	my $self = (shift)->new({'input' => shift || {}});

	my $employeeID = $self->input->{employeeID} || 0;
	$self->data->{'dataType'} = 'json';
	my ($previousRunStatus) = $self->dbhr->selectrow_array("SELECT status FROM runBatchLog ORDER BY runBatchLogID DESC LIMIT 1");
	$self->data->{'data'}->{'msg'} = '';
	if ($previousRunStatus && $previousRunStatus =~ /STARTED|RUNNING/i) {
		$self->data->{'data'}->{'msg'} = "Previous Batch is still running. Please wait till it is finished.";
		return $self->result;
	}

	$self->dbh->do("INSERT INTO runBatchLog (userID, startAt, status) VALUES (?, NOW(), 'STARTED')", undef, ($employeeID));

	return $self->result;
}

###############################################################################

sub getBatchInfo {
	my $self = (shift)->new({'input' => shift || {}});
	$self->data->{'dataType'} = 'json';

	my $previousRun = $self->dbhr->selectrow_hashref("SELECT employeeInfo.username, status, startAt, endAt FROM runBatchLog JOIN employeeInfo on runBatchLog.userID = employeeInfo.employeeID ORDER BY runBatchLogID DESC LIMIT 1");

	$self->data->{'data'} = {
		username => $previousRun->{username},
		status => $previousRun->{status},
		startAt => $previousRun->{startAt},
		endAt => $previousRun->{endAt},
	};
	if ($previousRun->{status} =~ /STARTED|RUNNING/i) {
		$self->data->{'data'}->{disable} = 1;
	}
	return $self->result;
}

return 1;

