<?php
// fetch the Firmata board depending on the configuration
$board = include(__DIR__.'/bootstrap.php');

// Carica Chip is used
use Carica\Chip as Chip;
// and http from Carica Io
use Carica\Io\Network\Http as Http;

$board
  ->activate()
  ->done(
    function () use ($board) {
      // Create the led object
      $led = new Chip\Led($board->pins[13]);

      // Create a new route for the http server
      $route = new Http\Route();
      // Define html file delivery for /
      $route->match(
        '/',
        new Http\Route\File(__DIR__.'/index.html')
      );

      // define a route for the led switch requests
      $route->match(
        '/switch/{state}',
        function (Http\Request $request, array $parameters) use ($led) {
          // check the state parameter
          $ledOn = ($parameters['state'] == 'on');
          // switch the led
          if ($ledOn) {
            $led->on();
          } else {
            $led->off();
          }
          // create an response
          $response = $request->createResponse(
            new Http\Response\Content\String(
              $ledOn ? 'ON' : 'OFF',
              'text/plain; charset=utf-8'
            )
          );
          return $response;
        }
      );

      // create the http server
      $server = new Carica\Io\Network\Http\Server($route);
      // listen on port 8080
      $server->listen(8080);
    }
  );

// start the event loop
Carica\Io\Event\Loop\Factory::run();