<?php

/**
 * Decide on text color based on background
 * @param  string $hexcolor Background Color
 * @param  string $dark     Dark contrast colour
 * @param  string $light    Light contrast colour
 * @return string           Color
 */
function get_contrast($hexcolor, $dark = 'black', $light = 'white')
{
    if (substr($hexcolor, 0, 1) == '#') {
        $hexcolor = substr($hexcolor, 1);
    }

    $r = hexdec(substr($hexcolor, 0, 2));
    $g = hexdec(substr($hexcolor, 2, 2));
    $b = hexdec(substr($hexcolor, 4, 2));

    $yiq = (($r * 299) + ($g * 587) + ($b * 114)) / 1000;

    return ($yiq >= 128) ? $dark : $light;
}

/**
 * Retrieve meta data about attachments
 * @param  integer $attachment_id Attachment ID
 * @param  array   $size          Image Size
 * @return array                  Details
 */
function wp_get_attachment($attachment_id, $size = [])
{
    $src        = wp_get_attachment_image_src($attachment_id, $size);
    $attachment = get_post($attachment_id);

    // Attachment doesn't exist
    if (!$src) {
        return false;
    }

    return [
        'alt'         => get_post_meta($attachment->ID, '_wp_attachment_image_alt', true),
        'caption'     => $attachment->post_excerpt,
        'description' => $attachment->post_content,
        'href'        => get_permalink($attachment->ID),
        'src'         => $src[0],
        'width'       => $src[1],
        'height'      => $src[2],
        'title'       => $attachment->post_title
    ];
}

/**
 * Make sure HTTP has been added to URL
 * @param  string $url URL
 * @return string      Fixed URL
 */
function check_url($url)
{
    if (substr($url, 0, 1) != '#' && substr($url, 0, 4) != 'http') {
        return 'http://' . $url;
    }

    return $url;
}

/**
 * Get menu name by theme location
 * @param  string $location Location slug
 * @return string           Menu name
 */
function get_menu_name_from_location($location)
{
    $locations = get_nav_menu_locations();
    $menu = wp_get_nav_menu_object($locations[$location]);

    return $menu->name;
}

/**
 * Array map with preserved keys
 * @param  function $callback Callback function
 * @param  array    $array    Array to iterate over
 * @return array              Newly mapped array
 */
function array_map_with_keys($callback, $array)
{
    $keys = array_keys($array);

    return array_combine($keys, array_map($callback, $keys, $array));
}
