<?php
require __DIR__ . '/../bootstrap.php';

function hathor_home() {
  $artists = get_artists();
  $length = count($artists);
  $ret['status'] = 200;
  $ret['count'] = $length;
  $ret['response'] = $artists;
  $app = \Slim\Slim::getInstance();
  $app->response->setBody( \Hathor\Format::tojson($ret) );

}

function hathor_get_error($type = HATHOR_NO_RESULTS) {
 // print_r(json_decode('{"errors":[{"code":215,"message":"Bad Authentication data."}]}'));
 
  $error['errors'][] = [
        'code' => 404,
        'message' => 'No results found.'
      ];

  return \Hathor\Format::tojson($error);
}
function hathor_years_get_options() {

  $return['GET'][] =
    [
      'int' => 'year',
      'description' => 'The year of the album'
    ];

  return \Hathor\Format::tojson($return, true);
}

$app->get('/track/play/:tid', function($tid) use ($app) {

      $track = get_track($tid);
       $app->response->headers->set('Content-Type', 'audio/mpeg');
       $app->response->setBody( file_get_contents( $track['uri'] ) );
       /*$content = base64_encode( file_get_contents( $track['uri'] ) );
       if( file_exists( dirname($track['uri']) . DIRECTORY_SEPARATOR . 'album.jpg' ) ):
        $albumart = base64_encode( file_get_contents( dirname($track['uri']) . DIRECTORY_SEPARATOR . 'album.jpg' ) );
       else:
        $albumart = base64_encode( file_get_contents( 'http://placekitten.com/120/121' ) );
       endif;

       print sprintf('<img src="data:image/jpeg;base64,%s" />', $albumart);
      print sprintf('<audio id="player" src="data:audio/mpeg;base64,%s" controls preload="auto" autobuffer></audio>', $content);
      */
  }
);
function get_track($tid) {
  global $config;
   $pdo = new Hathor\Connection();
     //get_connection($config['db']);
  $selectStatement = $pdo->select()
  ->from('tracks')
  ->where('tid','=', $tid);
  $stmt = $selectStatement->execute();
  $ret = $stmt->fetch();
  close_connection($pdo);
  return $ret;
}

function hathor_get_album($aid) {
    $app = \Slim\Slim::getInstance();
    global $config;

    $album = get_album($aid);
    $request = $app->request;
    $res = $app->response;

    $res->headers->set('Content-Type', 'application/json');
    $res->setStatus(200);

    if($request->isOptions()):
      $res->headers->set('Allow', 'GET, OPTIONS');
      $res->setBody("200 OK\nAllow: GET,OPTIONS\n");
    else:
      $json['status'] = 200;

      foreach($config->defaults['cover_files'] as $cover):
        if( file_exists( dirname($album[0]['uri']) . DIRECTORY_SEPARATOR . $cover ) ):
          $albumcover = dirname($album[0]['uri']) . DIRECTORY_SEPARATOR . $cover;
          break;
        else:
          continue;
        endif;
      endforeach;
      if(isset($albumcover)):
        $meta = getimagesize($albumcover, $info);
        $meta = array(
          'width' => $meta[0],
          'height'=> $meta[1],
          'bits'  => isset($meta['bits']) ? $meta['bits'] : null,
          'mime'  => isset($meta['mime']) ? $meta['mime'] : null,
          'extra'  => empty($info) ? null : $info
        );
        $cover = array(
          'base64' => base64_encode( file_get_contents( $albumcover ) ),
          'uri'    => $albumcover,
          'size'   => \Hathor\Format::tokb( filesize($albumcover) ),
          'meta'   => $meta
        );

      else:
        $meta = getimagesize(__DIR__ . DIRECTORY_SEPARATOR . '../images/album.jpg', $info);
        $meta = array(
          'width' => $meta[0],
          'height'=> $meta[1],
          'bits'  => isset($meta['bits']) ? $meta['bits'] : null,
          'mime'  => isset($meta['mime']) ? $meta['mime'] : null,
          'extra'   => empty($info) ? null : $info
        );
        $cover = array(
          'base64' => base64_encode( file_get_contents( __DIR__ . DIRECTORY_SEPARATOR . '../images/album.jpg' ) ),
          'uri'    => $request->getResourceUri(),
          'size'   => filesize(__DIR__ . DIRECTORY_SEPARATOR . '../images/album.jpg'),
          'meta'   => $meta
        );
      endif;

      foreach($album as $track):
        $tr[ $track['track'] ] = array(
          'tid'       => $track['tid'],
          'title'     => $track['title'],
          'genre'     => $track['genre'],
          'track'     => $track['track'],
          'length'    => $track['length'],
          'playtime'  => sprintf('%d:%02d',$track['minutes'], $track['seconds']),
          'size'      => sprintf('%.02f MB', ( filesize($track['uri']) / 1024 ) / 1024 )
        );
      endforeach;


      $json['response'] = array(
        'artist'  => $album[0]['artist'],
        'arid'    => $album[0]['arid'],
        'album'   => $album[0]['album'],
        'aid'     => $album[0]['aid'],
        'cover'   => $cover,
        'total'   => count($tr),
        'tracks'  => $tr
      );

      $res->setBody( json_encode($json) );
    endif;


  }

function get_album($aid) {
  global $config;
  $pdo = new Hathor\Connection();//get_connection($config['db']);
  $selectStatement = $pdo->select(
    array('tid','title','track','arid','artist','aid','album','year','genre','label','minutes','seconds','length','uri')
  )
    ->distinct()
    ->groupBy('tid')
    ->orderBy('track', 'ASC')
    ->from('tracks')
    ->where('aid','=',$aid);
  $stmt = $selectStatement->execute();
  $ret = $stmt->fetchAll();
  close_connection($pdo);
  return $ret;

}



$app->get('/artist/:arid', function ($arid) use($app) {
  $app->response->headers()->set('Content-Type','application/json');
  $app->response->setBody(json_encode(get_artist($arid)));
  })->conditions( array('id' => '[\w\d]+') );



function get_artist($arid) {
  global $config;
  $pdo = new Hathor\Connection();
  $selectStatement = $pdo->select(
    array('arid','artist')
  )
    //->distinct()
    ->groupby('arid')
    ->from('artists')
    ->where('arid','=',$arid);
  $stmt = $selectStatement->execute();
  $ret = $stmt->fetchAll();
  close_connection($pdo);
  return $ret;

}

function get_artists() {
  global $config;
  $test = new \Hathor\Connection();
  $pdo = new Hathor\Connection();
  $selectStatement = $pdo->select(array('name','arid'))
    ->orderBy('name')
    ->from('artists');
  $stmt = $selectStatement->execute();
  $ret = $stmt->fetchAll();
  close_connection($pdo);
  return $ret;
}

function get_years() {

}

function close_connection(\Slim\PDO\Database $db) {
  $db = null;
  return true;
}
$app->run();



