<?php
namespace TwigExtension;

use DI\Container;
use Helpers\Trad\Trad;

class HighchartsExtention extends \Twig\Extension\AbstractExtension
{
    /** @var Trad */
    protected $trad;

    /** @var Container */
    protected $container;

    public function __construct(Container $container)
    {
        $this->container = $container;
        $this->trad = $container->get(\Helpers\Trad\ITrad::class);
    }

    public function getFunctions()
    {
        return [
            new \Twig\TwigFunction('Highcharts', [
                $this,
                'Highcharts'
            ], [
                'is_safe' => [
                    'html'
                ]
            ]),
            new \Twig\TwigFunction('progressBar', [
                $this,
                'progressBar'
            ], [
                'is_safe' => [
                    'html'
                ]
            ])
        ];
    }
    
    // phpcs:ignore
    public function Highcharts($data)
    {
        $html = '';
        $idGraph = random_int(0, 999999999);

        if ($data['type']=='solidgauge') {
            $html .= "<div id='graph".$idGraph."'></div><script type='text/javascript'>
                var gaugeOptions".$idGraph." = {

                    chart: {
                        type: 'solidgauge',
                        //margin : 5,
                        style: {
                            fontFamily: '\"Segoe UI\", Helvetica, Arial, sans-serif'
                        },
                    },

                    credits: {
                        //enabled: false
                        href: 'https://oxalys.com',
                        text: 'Oxalys'
                    },
                
                    title: {
                        text: ".json_encode($data['titre']).",
                        margin : -50,
                    },
                
                    pane: {
                        center: ['50%', '85%'],
                        size: '100%',
                        startAngle: -90,
                        endAngle: 90,
                        background: {
                            innerRadius: '60%',
                            outerRadius: '100%',
                            shape: 'arc'
                        }
                    },
                
                    tooltip: {
                        enabled: false
                    },
                
                    // the value axis
                    yAxis: {
                        ".($data['patern_color']??'')."
                        lineWidth: 0,
                        minorTickInterval: null,
                        tickAmount: 2,
                        title: {
                            y: -70
                        },
                        labels: {
                            y: 16
                        }
                    },
                
                    plotOptions: {
                        solidgauge: {
                            dataLabels: {
                                y: 5,
                                borderWidth: 0,
                                useHTML: true
                            }
                        }
                    }
                };
                
            Highcharts.chart('graph".$idGraph."', Highcharts.merge(gaugeOptions".$idGraph.", {
                yAxis: {
                    min: ".$data['fourchette'][0].",
                    max: ".$data['fourchette'][1].",
                    tickPositions: [".$data['fourchette'][0].",         ".$data['fourchette'][1]."],
                    labels: {enabled:".(($data['fourchette'][2]??false)? 'false':'true')."},
                    ".($data['gauge_categorieY']??'')."
                },
                
                credits: {
                    enabled: false
                },

                lang: {
                    // Chart context menu
                    contextButtonTitle: '" . addslashes($this->trad->t('Options d\'export')) . "', 
                    viewFullscreen : '" . addslashes($this->trad->t('Afficher en plein écran')) . "', 
                    printChart:   '" . addslashes($this->trad->t('Imprimer le graphique')) . "',
                    downloadPNG:  '" . addslashes($this->trad->t('Télécharger une image PNG')) . "',
                    downloadJPEG: '" . addslashes($this->trad->t('Télécharger une image JPEG')) . "',
                    downloadPDF:  '" . addslashes($this->trad->t('Télécharger une image en document PDF')) . "',
                    downloadSVG:  '" . addslashes($this->trad->t('Télécharger une image vectorielle SVG')) . "',
                    downloadCSV:  '" . addslashes($this->trad->t('Télécharger les données dans un fichier CSV')) . "',
                    downloadXLS:  '" . addslashes($this->trad->t('Télécharger les données dans un fichier Excel')) . "',
                    viewData: '" . addslashes($this->trad->t('Afficher les données')) . "',
                    // Zoom
                    resetZoom:    '" . addslashes($this->trad->t('Supprimer le zoom')) . "',
                    resetZoomTitle: 'Zoom 1:1',
                    thousandsSep: ' ',
                    numericSymbols: [null,' M',' G',' T',' P',' E']
                },
                
                series: [{
                    data: [".$data['value']."],
                    dataLabels: {
                        format: '<div style=\"text-align:center\"><span style=\"font-size:25px;color:' +
                            ((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '\">".($data['categorieY']? '':'{y}')."</span><br/>' +
                               '<span style=\"font-size:14px;color:silver\">".$data['legendGraph']."</span></div>'
                    },
                    tooltip: {
                        valueSuffix: ' ".$data['legendGraph']."'
                    }
                }]
                
            }));";
            
            $html .= "</script>";
        } elseif ($data['type']=='spiderweb') {
            $html .= "<div id='graph".$idGraph."'></div><script type='text/javascript'>
                    $(function () {
                        $('#graph".$idGraph."').highcharts({
                            chart: {
                                polar: true,
                                type: 'line',
                                style: {
                                    fontFamily: '\"Segoe UI\", Helvetica, Arial, sans-serif'
                                }
                            },
                            credits: {
                                //enabled: false
                                href: 'https://oxalys.com',
                                text: 'Oxalys'
                            },
                	        title: {
                	            text: ".json_encode($data['titre']).",
                	        },
                            pane: {
                                size: '70%'
                            },";
            $html .= "
                            xAxis: [{
                                tickmarkPlacement: 'on',
                                lineWidth: 0,
                	            categories: [";
            foreach ($data['ListeCategorie'] as $value) {
                $html .= "'".$value."',";
            }
            $html .= "          ],
                            }],
                            yAxis: {
                                gridLineInterpolation: 'polygon',
                                lineWidth: 0,
                    			min: 0,
                                ".($data['maxValue']? "max : ".$data['maxValue'].",":"")."
                            },
                            tooltip: {
                                shared: true,
                            },
                            series: [".$data['value']."],
                     ";
            $html .="   });
                    });
            ";
            
            $html .= "</script>";
        } else {
            $html = "
            
                <div id='graph".$idGraph."' style='max-width:800px; margin: 0 auto;'></div>
                <script type='text/javascript'>
                $(function () {
                    Highcharts.setOptions({
                        // Trad.
                        lang: {
                            // Chart context menu
                            contextButtonTitle: '" . addslashes($this->trad->t('Options d\'export')) . "', 
                            viewFullscreen : '" . addslashes($this->trad->t('Afficher en plein écran')) . "', 
                            printChart:   '" . addslashes($this->trad->t('Imprimer le graphique')) . "',
                            downloadPNG:  '" . addslashes($this->trad->t('Télécharger une image PNG')) . "',
                            downloadJPEG: '" . addslashes($this->trad->t('Télécharger une image JPEG')) . "',
                            downloadPDF:  '" . addslashes($this->trad->t('Télécharger une image en document PDF')) . "',
                            downloadSVG:  '" . addslashes($this->trad->t('Télécharger une image vectorielle SVG')) . "',
                            downloadCSV:  '" . addslashes($this->trad->t('Télécharger les données dans un fichier CSV')) . "',
                            downloadXLS:  '" . addslashes($this->trad->t('Télécharger les données dans un fichier Excel')) . "',
                            viewData: '" . addslashes($this->trad->t('Afficher les données')) . "',
                            // Zoom
                            resetZoom:    '" . addslashes($this->trad->t('Supprimer le zoom')) . "',
                            resetZoomTitle: 'Zoom 1:1',
                            thousandsSep: ' ',
                            numericSymbols: [null,' M',' G',' T',' P',' E']
                        }
                    });                    

                	    $('#graph".$idGraph."').highcharts({
                	        chart: {
                	            type:".json_encode($data['type']).",
                                zoomType: 'xy',
                                panning: true,
                                panKey: 'shift',
                                style: {
                                    fontFamily: '\"Segoe UI\", Helvetica, Arial, sans-serif'
                                }
                	        },
                            subtitle: {".$data['subTitle']."},
                            credits: {
                                //enabled: false
                                href: 'https://oxalys.com',
                                text: 'Oxalys'
                            },
                	        title: {
                	            text: ".json_encode($data['titre']).",
                	        },";
        
                            /* X / Y */
        
            if ($data['type']=='bar' || $data['type']=='column' || $data['type']=='area') {
                $html .=           "xAxis: [{
                                        	            categories: [";
                foreach ($data['ListeCategorie'] as $value) {
                    $html .= "'".$value."',";
                }
                                $html .=                "],
                                                        labels: {
                                                            formatter: function () {
                                                                var val = this.value;
                                                                var words = val.split(' - ');
                                                                return words[0];
                                                            },
                                                        },
                                        	            crosshair: true,
                                        	        }],
                                                    ".($data['legendGraph']? "yAxis: [".$data['legendGraph']."],":"");
            }

                            $html .= "        plotOptions: {";

            if ($data['stacking']) {
                $html .= "  column: {
                                stacking: '".$data['stacking']."'
                        }, ";
            }

            if ($data['path']) {
                $html .= "          series: {
                                                        cursor: 'pointer',
                                                        point: {
                                                            events: {
                                                                click: function () {

                                                                    if(this.x+1<10)
                                                                        mois = '0'+  parseInt(this.x+1);
                                                                    else
                                                                        mois =  parseInt(this.x+1);

                                                                    redirectJSWithPost( '".$data['path']."' , $.extend(".$data['pathPost'].", {mois : mois}));
                                                                    //redirectJSWithPost( '".$data['path']."' , ".$data['pathPost'].");
                                                                }
                                                            }
                                                        }
                                                    },
                                ";
            }
                            /* donut  */
            if ($data['type']=='pie') {
                $html .= "
                                    pie: {
                                        shadow: false,
                        				dataLabels: {
                        					enabled: false
                        				},
                                        point:{
                                           events : {
                                                legendItemClick: function(e){
                                                    e.preventDefault();
                                                }
                                           }
                                        },
                                    },
                            ";
            }
                                                        
            $html .=       "},tooltip: {
                    shared: false,
                    useHTML: true";

            if ($data['categorieY']) {
                $html .= "formatter: function () {
                                                var labels = [";
                foreach ($data['categorieY'] as $catY) {
                    $html .= "'$catY',";
                }
                            ;
                $html .= "  ];
                                                return labels[this.y]
                                            },";
            }
            $html .=       "},
                	        series: [".$data['value']."],
                            legend: {".$data['legend']."},
                	    });
                });";

                $html .= "</script>";
        }

        return $html;
    }
    
    /**
     * progressBar
     * @param mixed $dataArray va nous permettre de rajouter des parametre pour personnaliser notre progressBar
     * @return mixed
     */
    public function progressBar($dataArray)
    {
        $id= uniqid(4);
        $html = "
        <div id = 'containerProgressBar".$id."'></div>
        <script>
        
        var chart = new Highcharts.Chart({
            title: {
              text: 'Etat D\'avancement:',
              align: 'left',
              margin: 0,
            },
            chart: {
              renderTo: 'containerProgressBar".$id."',
              type: 'bar',
              height: 70,
              align: 'right',
              backgroundColor: 'none',
            },
            credits: false,
            tooltip: false,
            legend: false,
            navigation: {
              buttonOptions: {
                enabled: false
              }
            },
            xAxis: {
              visible: false,
            },
            yAxis: {
              visible: false,
              min: 0,
              max: 100,
            },
            series: [{
              data: [100],
              grouping: false,
              animation: false,
              enableMouseTracking: false,
              showInLegend: false,
              color: 'grey',
              pointWidth: 45,
              borderWidth: 0,
              borderRadiusTopLeft: '4px',
              borderRadiusTopRight: '4px',
              borderRadiusBottomLeft: '4px',
              borderRadiusBottomRight: '4px',
              dataLabels: {
                className: 'highlight',
                format: '100%',
                enabled: true,
                align: 'right',
                style: {
                  color: 'white',
                  textOutline: false,
                }
              }
            }, {
              enableMouseTracking: false,
              data: [45],
              borderRadiusBottomLeft: '4px',
              borderRadiusBottomRight: '4px',
              color: 'navy',
              borderWidth: 0,
              pointWidth: 25,
              animation: {
                duration: 800,
              },
              dataLabels: {
                enabled: true,
                inside: true,
                align: 'left',
                format: '{point.y}%',
                style: {
                  color: 'white',
                  textOutline: false,
                }
              }
            }]
          });
            </script>
        ";

        return $html;
    }
}
