<?php

if (!function_exists('link_transform')) {
  function link_transform($link)
  {
    $link = json_decode($link);
    if ($link->label === '') return FALSE;
    if ($link->isExternal) {
      $finalUrl = isset($link->url) ? $link->url : '';
    } else {
      $entry = WebsiteObject::select('website_object_id', 'slug')
        ->where('website_object_id', $link->objectId)
        ->first();
      $finalUrl = $entry->slug;
    }

    $out = [
      'label'      => isset($link->label) ? $link->label : '',
      'isExternal' => $link->isExternal ? $link->isExternal : FALSE,
      'url'        => $finalUrl
    ];


    return $out;
  }
}

if (!function_exists('getImageSizes')) {
  /**
   * Retrieves a Media sizes for the current type which should define the
   * correct image ratios
   * @param  string $image_name name of the image
   * @param  string $type the tumbnail size to get the sizes from
   * @return array              Image size data
   */
  function getImageSizes($image_name, $type) {
    $path = getMediaPath($image_name, $type);
    $sizes = [];
    if (file_exists($path)) {
      $sizes = getimagesize($path);
    }
    return $sizes;
  }
}

if (!function_exists('responsiveImages')) {
  /**
   * Creates an array for the responsive image handling in the frontend
   * @param  string $image_name name of the image
   * @return array              Array with the needed sizes for the srcset
   */
  function responsiveImages($image_name, $sizes)
  {
    $images = [];
    if (!empty($image_name)) {
      foreach ($sizes as $key => $size) {
        // Retrieve image thumbnail size
        $tmp = getMediaUrl($image_name, $key);
        $images[$size] = $tmp;
      }
    }
    return $images;
  }
}

if (!function_exists('base64Image')) {

  /**
   * Retrieves a Media path and generates a base64 encoded string out of it
   * @param  string $image_name name of the image
   * @param  string $type the tumbnail size to read the data from
   * @return string             base 64 encoded string to be used in an img
   */
  function base64Image($image_name, $type) {
    $path = getMediaPath($image_name, $type);
    $base64Image = '';
    if (file_exists($path)) {
      $type = pathinfo($path, PATHINFO_EXTENSION);
      $data = file_get_contents($path);
      $base64Image = 'data:image/' . $type . ';base64,' . base64_encode($data);
    }
    return $base64Image;
  }
}

if (!function_exists('allowedHtmlTags')) {

  /**
   * Retrieves the allowed HTML tags for the transformers
   * @return string
   */
  function allowedHtmlTags() {
    return '<h1><h2><h3><h4><h5><h6><p><a><br><ul><ol><li><br><strong><em><del><u>';
  }
}
