<?php

  use ColorThief\ColorThief;

$function = new Twig_SimpleFunction('bgcolor', function ($fileName){

    if (!function_exists('rgb2hex')) {
      function rgb2hex($rgb) {
         $hex = "#";
         $hex .= str_pad(dechex($rgb[0]), 2, "0", STR_PAD_LEFT);
         $hex .= str_pad(dechex($rgb[1]), 2, "0", STR_PAD_LEFT);
         $hex .= str_pad(dechex($rgb[2]), 2, "0", STR_PAD_LEFT);
    
         return $hex; // returns the hex value including the number sign (#)
      }
    }
    
    $documentRoot = trim(getcwd(), "pattern-lab") . '/source/';
    $newfileName = str_replace('/images', 'images', $fileName);
    $filePath = $documentRoot . $newfileName;
      

    if ($fileName !== '' && file_exists($filePath)) {
      $color = ColorThief::getColor($filePath, 10);
      $hex = rgb2hex($color);
    }
      
    if (isset($hex)){
      return $hex;
    } else {
      return 'transparent';
    }

  });
?>
