### ----------------------------------------------------
### -- Sparky
### -- Licenses: Artistic-2.0
### -- Authors: Alexey Melezhik
### -- File: bin/sparky-web.raku
### ----------------------------------------------------
### -- Chunk 2 of 2
 say "auth: token recieved - {%data<access_token>} ... ";

        say "auth: request user data using {sparky-auth()<user_api>} ...";

        $id_tmp = "{('a' .. 'z').pick(20).join('')}.{$*PID}";

        shell qq:to /CURL/;
        curl -H "Authorization: Bearer {%data<access_token>}" \\
        {sparky-auth()<user_api>} \\
        -f -L -s -o {cache-root()}/users/user_{$id_tmp}.json
        CURL

        my $data2 = "{cache-root()}/users/user_{$id_tmp}.json".IO.slurp;

        say "auth: use data recieved - {$data2}";
  
        my %data2 = from-json($data2);

        unlink "{cache-root()}/users/user_{$id_tmp}.json";

        say "auth: {%data2.perl}";

        %data2<login> = %data2<username>;

        say "oauth2 protocol: set user login to {%data2<username>}";

        my $date = DateTime.now.later(years => 100);

        set-cookie 'user', %data2<login>, http-only => True, expires => $date;

        set-cookie 'token', user-create-account(%data2<login>,%data2), http-only => True, expires => $date;

        redirect :see-other, "{sparky-http-root()}/?message=user [{%data2<name>}] logged in&level=info";

      } else {

        redirect :see-other, "{sparky-http-root()}/?message=issues with login&level=info";

      }
      
  }

  #
  # End of Authentication methods
  #

  #
  # Static files methods
  #

  get -> 'js', *@path {
    cache-control :public, :max-age(300);
    static 'js', @path;
  }

  get -> 'css', *@path {
    cache-control :public, :max-age(10);
    static 'css', @path;
  }

  #
  # End of Static files methods
  #

}

}

my $pool;

if get-database-engine() ne "sqlite" {

    my %conf = get-sparky-conf();
    my %connection-parameters = 
        host      => %conf<database><host>,
        port      => %conf<database><port>,
        database  => %conf<database><name>,
        user      => %conf<database><user>,
        password  => %conf<database><pass>;

    my $pool = DBIish::Pool.new(
      driver => get-database-engine(), 
      max-connections => 50, 
      max-idle-duration => Duration.new(60),
      min-spare-connections => 3,  
      initial-size => 5, 
      |%connection-parameters
    );

}

my $application = create-cro-app($pool);

(.out-buffer = False for $*OUT, $*ERR;);

my $port = sparky-tcp-port();

my $host = sparky-host();

say "run sparky web ui on host: {$host}, port: {$port} ...";

my Cro::Service $service;

if sparky-use-tls() {

  say "use tls mode ...";

  my %tls = sparky-tls-settings();

  say "load tls settings: ", %tls.perl;

  $service = Cro::HTTP::Server.new: :$host, :$port, :$application, :%tls;

} else {

  $service = Cro::HTTP::Server.new: :$host, :$port, :$application;
}

$service.start;

react whenever signal(SIGINT) {
    $service.stop;
    exit;
}


