<?php

function sortArray($x, $y, $sort = 'asc')
{
    if($sort == 'asc') asort($x);
    if($sort == 'desc') arsort($x);

    $sortY = array();
    foreach($x as $index => $value)
    {
        $sortY[] = $y[$index];
    }

    return array(array_values($x), array_values($sortY));
}

function getOrderCustom($datas)
{
    return range(1, count($datas));
}

function getDisOrderCustom($datas, $unsortDatas)
{
    $indexs = array();
    foreach($datas as $data)
    {
        $index    = array_search($data, $unsortDatas);
        $indexs[] = $index != -1 ? $index + 1 : 'null';
    }

    return $indexs;
}

function setDataHover($data, $template, $custom = array())
{
    $data['hoverinfo']     = 'none';
    $data['hovertemplate'] = $template;

    if(!empty($custom)) $data['customdata'] = $custom;

    return $data;
}

function getHoverTemplateX($data, $params)
{
    global $dasLang;

    $haveX = isset($params['xname']);
    if(!$haveX) return $data;

    $xname     = $params['xname'];
    $custom    = $params['custom'];
    $extraText = isset($params['extra']) ? $params['extra'] : '';

    $template = $dasLang->column . "%{customdata}: ($xname=%{x})";
    if($extraText) $template .= " <extra>$extraText</extra>";

    return setDataHover($data, $template, $custom);
}

function getHoverTemplateY($data, $params)
{
    global $dasLang;

    $haveY = isset($params['yname']);
    if(!$haveY) return $data;

    $yname     = $params['yname'];
    $custom    = $params['custom'];
    $extraText = isset($params['extra']) ? $params['extra'] : '';

    $template = $dasLang->column . "%{customdata}: ($yname=%{y})";
    if($extraText) $template .= " <extra>$extraText</extra>";

    return setDataHover($data, $template, $custom);
}

function getHoverTemplateXY($data, $params)
{
    global $dasLang;

    $haveXY = (isset($params['xname']) && isset($params['yname']));
    if(!$haveXY) return $data;

    $xname     = $params['xname'];
    $yname     = $params['yname'];
    $custom    = isset($params['custom']) ? $params['custom'] : array();
    $extraText = isset($params['extra'])  ? $params['extra']  : '';

    if(!empty($custom))
    {
        $template = $dasLang->column . "%{customdata}: ($xname=%{x},$yname=%{y})";
    }
    else
    {
        $template = $dasLang->column . "($xname=%{x},$yname=%{y})";
    }
    if($extraText) $template .= " <extra>$extraText</extra>";

    return setDataHover($data, $template, $custom);
}

function getChartRange($min, $max, $tolerance = 0.05)
{
    $toleranceValue = ($max - $min) * $tolerance;
    return array($min - $toleranceValue, $max + $toleranceValue);
}
