#!/usr/bin/perl -Ilibs

package API::Controller;

use strict;
use warnings;

use Moose;

use API::Config;

use lib ($API::Config::Config->{'Website_libs'});
use ECS::DB;
use ECS::dbConfig;

has 'data' => (
    'is'        => "rw",
    'isa'       => "HashRef",
    'default'   => sub { {} },
);

has 'dbh' => (
    'is'    => "rw",
    'isa'   => "DBI::db",
    'lazy_build' => 1,
);

has 'dbhr' => (
    'is'    => "rw",
    'isa'   => "DBI::db",
    'lazy_build' => 1,
);

has 'error' => (
    'is'        => "rw",
    'isa'       => "Str",
    'default'   => "",
    'trigger'   => sub { $_[0]->success(0) },
);

has 'input' => (
    'is'    => "ro",
    'isa'   => "HashRef",
);

has 'success' => (
    'is'        => "rw",
    'isa'       => "Bool",
    'default'   => 1,
);

has 'parameters' => (
    'is'  => "ro",
    'isa' => "Maybe[SOAP::SOM]",
);

around 'BUILDARGS' => sub {
    my $orig = shift;
    my $class = shift;

    if(@_ > 1) {
        return $class->$orig({
            'input'      => shift || {},
            'parameters' => shift || undef,
        });
    }
    else {
        return $class->$orig(@_);
    }
};

__PACKAGE__->meta->make_immutable;

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

sub result {
    my $self = shift;

    return {
        'data'      => $self->data,
        'success'   => $self->success,
        'error'     => $self->error,
        'update_DB' => 1,
        };
}

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

sub _build_dbh {
    return ECS::DB->connect({'config' => $ECS::dbConfig::db{'mysql'}});
}

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

sub _build_dbhr {
    return ECS::DB->connect({'config' => $ECS::dbConfig::db{'mysqlSlave'}, readonly => 1 });
}

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

return 1;

