<?php

/** @var yii\web\View $this */

use yii\helpers\Html;
use yii\web\View;
use app\modules\ldjson\jsonLD;

$this->title = 'Барнаул погода';

$url =  '/weather';
$this->params['breadcrumbs'] = [
    [
        "text"=>$this->title,
        "url"=>$url
    ]
];

$addtpage = ' amic.ru';

Yii::$app->og->title = $this->title.$addtpage;
Yii::$app->og->description ='Погода в Алтайском крае - '.Yii::$app->og->description.$addtpage;
Yii::$app->og->og_title = str_replace( '"',"&quot;", $this->title );
Yii::$app->og->og_description = str_replace( '"',"&quot;",Yii::$app->og->description);
Yii::$app->og->canonical = $url;
Yii::$app->og->og_type = "website";

jsonLD::addAmicORG();
$i = 1;
foreach($this->params['breadcrumbs'] as $el){
	jsonLD::addBreadcrumb($i, $el['url'], $el['text']);
	$i++;
}


$cat = '/home/admin/import/';

$data = [
    '160.xml',
    '150.xml',
    '157.xml',
    '7591.xml',
    '7586.xml',
    '7306.xml'
];


$precipitationi = [
            1 => '',
            2 => '',
            3 => '', // снег дождь
            4 => 'Cloud-Rain.svg',
            5 => 'Cloud-Hail.svg',
            6 => 'Cloud-Hail.svg', //снег
            7 => 'Cloud-Hail-Alt.svg', //снег
            8 => 'Cloud-Lightning.svg',
            9 => '',
            10 => ''
];    
$cloudsi = [
            -1 => '', // - туман
            0 => 'Sun.svg',
            1 => 'Cloud-Sun.svg',  //  'Малооблачно',
            2 => 'Cloud.svg', //    'Облачно',
            3 => 'Cloud.svg', //    'Пасмурно'
];

?>
<div class="site-weather">
    <div class="row">
        <div class="col-md-8 mt-3 bg-white">
    <h1>Погода в Алтайском крае</h1>
<?        
        if( file_exists( '/home/admin/temp/temperature' ) ){
            echo "<p><big>Сейчас в Барнауле ".file_get_contents( '/home/admin/temp/temperature' )."<sup>o</sup>C &nbsp;&nbsp;</big></p>";
        }

        $cd ='';
        if( file_exists( $cat.'solar3.json' ) ){
            $strn = @file_get_contents( $cat.'solar3.json' );
//            $date = filemtime( $cat.'solar3.json' );
            $solarnow = json_decode( $strn );
            foreach($solarnow as $c) {
				if( $c < 4 ){
					$cd .= '"#00ff00",';
				}elseif( $c > 5 ){
					$cd .= '"#ff0000",';
				}else{
					$cd .= '"#ffd810",';
				}

            }
		}
        $ss = '"6:00","10:00","14:00","18:00","22:00","00:00"';

        if( file_exists( $cat.'solar.json' ) ){
            $str = @file_get_contents( $cat.'solar.json' );
            $date = filemtime( $cat.'solar.json' );
            $solar = json_decode( $str );
            $s = '';
            for( $i = 1; $i < 27; $i++ ){
                $s .= date('"d M"',$date+$i*86400).',';
            }

?>

<div class="row mb-4">
<div class="col-sm ml-auto" style="box-shadow: 2px 2px 7px #888;">
  <canvas id="myChart0"></canvas>
</div>
<div class="col-sm" style="box-shadow: 2px 2px 7px #888;">
  <canvas id="myChart"></canvas>
</div>
</div>
<?

?>
<script src='/js/chart.js'></script>


<script>

  const ctx = document.getElementById('myChart');
  const ctx0 = document.getElementById('myChart0');

  let width, height, gradient;
function getGradient(ctx, chartArea) {
  const chartWidth = chartArea.right - chartArea.left;
  const chartHeight = chartArea.bottom - chartArea.top;
  if (!gradient || width !== chartWidth || height !== chartHeight) {
    // Create the gradient because this is either the first render
    // or the size of the chart has changed
    width = chartWidth;
    height = chartHeight;
    gradient = ctx.createLinearGradient(0, chartArea.bottom, 0, chartArea.top);
    gradient.addColorStop(0, 'green');
    gradient.addColorStop(0.5, 'red');
    gradient.addColorStop(1, '#960018');
  }

  return gradient;
}
  
  
  new Chart(ctx, {
    type: 'line',
    data: {
      labels: [<?=$s?>],
      datasets: [{
        label: 'Магнитные возмущения',
        data: <?=$str?>,
        borderWidth: 1,
        fill: true,
        tension: 0.5,
        pointRadius: 0,
        backgroundColor: function(context) {
        const chart = context.chart;
        const {ctx, chartArea} = chart;

        if (!chartArea) {
          // This case happens on initial chart load
          return;
        }
        return getGradient(ctx, chartArea);
      },
      }]
    },
    options: {
      scales: {
        y: {
          beginAtZero: true,
          min:0,
          max:10
        }
      }
    }
  });

  new Chart(ctx0, {
    type: 'bar',
    data: {
      labels: [<?=$ss?>],
      datasets: [{
        label: 'Магнитные возмущения сегодня',
        data: <?=$strn?>,
        borderWidth: 1,
        fill: true,
		backgroundColor: [<?=$cd?>]
      }]
    },
    options: {
      scales: {
        y: {
          beginAtZero: true,
          min:0,
          max:10
        }
      }
    }
  });



</script>

<?
//    $this->registerJs(
  //      "myChart = new Chart(document.getElementById('js-chart-1').getContext( '2d' ),config); console.log(config)",
    //    View::POS_END
    //);

        }

        foreach( $data as $file )
        {
            $str = @file_get_contents( $cat.$file );
            if( $str ){
                $xml = simplexml_load_string( $str );
                if( $xml ){
                    $town = rawurldecode( $xml->REPORT->TOWN['sname'] );
                    $town = ( $town == 'SLAVGOROD' )?'Славгород':$town;
                    $town = ( $town == "KAMEN'-NA-OBI" )?'Камень-на-Оби':$town;
                    $town = ( $town == "Заринск,+Алтайский+край,+Россия" )?'Заринск':$town;
                    echo "<h2>$town</h2><div class=\"town row justify-content-md-center mb-5 bg-white\">";
                    foreach( $xml->REPORT->TOWN->FORECAST as $w ){
                        $t_max = $w->TEMPERATURE['max'];
                        $t_min = $w->TEMPERATURE['min'];
                        $p_min = $w->PRESSURE['min'];
                        $p_max = $w->PRESSURE['max'];
                        $w_min = $w->WIND['min'];
                        $w_max = $w->WIND['max'];
                        $day = $w['day'];
                        $month = $w['month'];
                        $hour = $w['hour'];
                        $year = $w['year'];
                        $cloudiness = $w->PHENOMENA['cloudiness'];
                        $precipitation = $w->PHENOMENA['precipitation'];
?>
            <div class="hour col-md-3 p-2">
                <div class='date'>На <?=$hour?> час  <?=$day?>.<?=$month?>.<?=$year?></div>
                <p><big><b><?=$t_min?><sup>o</sup>C до <?=$t_max?><sup>o</sup>C</b></big></p>
                Давление <?=$p_min?>, <?=$p_max?>мм рт.ст.<br/>
                <span style = 'padding-top:5px'>Ветер <?=$w_min?>, <?=$w_max?>м/с</span>
                <div class="sign fleft col-3">
                <? if( $precipitationi["$precipitation"] !='' )
                {
                ?>
                    <img class="weathericon2" src="/img/weather/<?=($precipitationi["$precipitation"] !='' )?$precipitationi["$precipitation"]:'e.gif'?>" >
                <?
                }
                ?>
                    <img class="weathericon2" src="/img/weather/<?=($cloudsi["$cloudiness"] != '')?$cloudsi["$cloudiness"]:'e.gif'?>" >
                </div>
            </div>
    
<?
                    }
                    echo "</div>";
                }
            }
        }
?>
        <p><a href="https://www.meteoservice.ru/">«Предоставлено Meteoservice.ru»</a></p>
        </div>
        <div class="col-md-4">
        <?=$this->render("/layouts/lenta/temalenta", ['topic'=>89, 'items'=>20])?>
        </div>
    </div>
</div>
