#!/usr/bin/perl

use utf8;
use Mojolicious::Lite;
use Data::Dumper;
use FindBin qw( $Bin );
use lib "$Bin/lib";
use lib "/opt/pos/lib";
use App::POS::Config;
use App::POS::Machine::Server;

#plugin 'TemplateToolkit';
#app->renderer->paths(["$Bin/templates"]);

plugin Config => { file => "$Bin/etc/app.conf" };
plugin 'RenderFile';

#app->config(hypnotoad => {listen => ['http://*:3034']});

# takes care of cross domain issue
app->hook(before_dispatch => sub {
  my $s = shift;
  my $req = $s->req;

  $s->res->headers->header('Access-Control-Allow-Origin'  => '*');
  $s->res->headers->header('Access-Control-Allow-Methods' => '*');
  $s->res->headers->header('Access-Control-Max-Age'       => '3600');
  $s->res->headers->header('Access-Control-Allow-Headers' => '*');
});

get '/' => sub {
  my $s = shift;
  my $req = $s->req;
  my $config = $s->config; # app config
  my $db = $s->db;
  my $p = $req->params->to_hash;
  #my $p = $req->json;

  $s->reply->static('index.html');
};

#
# Helpers
#

helper l => sub {
  my $s = shift;
  my $m = shift;
  print STDERR "$m\n";
};

helper d => sub {
  my $s = shift;
  my $ref = shift;
  print STDERR Dumper($ref);
};

helper pos_config => sub {
  my $s = shift;
  return App::POS::Config->new( file => "/opt/pos/etc/config.ini" );
};

helper pos_config_loaded => sub {
  my $s = shift;
  my $cfg = $s->pos_config();
  return $cfg->load_fixed();
};

helper machine => sub {
  my $s = shift;
  my $cfg = $s->pos_config();
  return App::POS::Machine::Server->new( config => $cfg );
};

helper db => sub {
  my $s = shift;
  my $m = $s->machine();
  return $m->database();
};

helper json => sub {
  my $s = shift;
  my $r = shift;
  $r //= {};
  return $s->render(json => $r);
};

helper text => sub {
  my $s = shift;
  my $m = shift;
  $m //= "";
  return $s->render(text => $m);
};

#
# Routes
#

push @{ app->routes->namespaces }, 'App::POS::API';
(any '/api/:route_to')->to('api#route_to');

app->start;

