<?php

namespace Hwapx\Core\Controller;

use HwapX\Core\Library\Image;
use HwapX\Core\Library\Template;

class Assets {
  protected $image_formats = array('jpeg', 'png', 'gif', 'wbmp');
  protected $resize_modes  = array('pad', 'fit', 'fill');

  public function index($f3, $args) {
    $content = Template::instance()->asset($args[1]);
    if(!$content)
      $f3->error(404);
    else
      echo $content;
  }

  public function thumb($f3, $args) {
    $path  = $f3->get('UPLOADS').$args['file'];
    $parts = explode('.', $args['file']);
    $ext   = end($parts);
    $mode  = $args['mode'];

    if(!file_exists($path))
      $f3->error(404);

    if($ext === 'jpg')
      $ext = 'jpeg';

    if(!in_array($ext, $this->image_formats))
      $f3->error(400);

    if(!in_array($mode, $this->resize_modes))
      $f3->error(400);

    $thumbdir = $f3->get('TEMP').'thumb/';
    $thumbfile= $mode.'_'.$args['width'].'x'.$args['height'].'_'.$args['file'];
    $thumbpath= $thumbdir.$thumbfile;

    if(!is_dir($thumbdir))
      mkdir($thumbdir, \Base::MODE, true);

    if(file_exists($thumbpath)) {
      $image = new Image($thumbfile, null, $thumbdir);
    } else {
      $image = new Image($args['file'], null, $f3->get('UPLOADS'));
      switch ($mode) {
        case 'fit':
          $image->resize($args['width'], $args['height'], true, false);
          break;
        
        case 'fill':
          $image->resize($args['width'], $args['height'], true, true);
          break;

        case 'pad':
          $bg = new Image();
          $bg->create($args['width'], $args['height']);

          $image->resize($args['width'], $args['height'], false, true);

          $bg->overlay($image, Image::POS_Center | Image::POS_Middle);

          $image = $bg;
          break;
      }

      file_put_contents($thumbpath, $image->dump($ext));
    }

    $image->render($ext);
  }
}