<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\bootstrap\Progress;
use yii\bootstrap\Modal;

$this->title = 'Update';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="update-index">
	<?php
	$session = Yii::$app->session;
	if (isset($session['dataUpdate'])) {
		$dataUpdate = $session['dataUpdate'];
		$infoUpdate = array_reverse($dataUpdate);

		echo Progress::widget([
		    'percent' => 0,
		    'barOptions' => ['class' => 'progress-bar-success'],
	    	'options' => ['class' => 'active progress-striped']
		]);

		foreach ($dataUpdate as $key => $data) {
			unset($data['changelog']);
			unset($data['changed_files']);
			$dataUpdate[$key] = $data;  
		?>
			<div>
				<span class="update-icon"><i id ="icon<?= str_replace('.', '-', $data['version']) ?>" class="fa fa-square-o"></i></span> Update to version <?= $data['version'] ?>
			</div>
		<?php
		}

		Modal::begin([
			'footer' => '<button class="btn btn-primary btn-close">OK</button>'
	    ]);
	    echo 'Update done!';
	    Modal::end();
	    ?>

	    <button class="btn btn-primary update-btn start-update">Start Update Process</button>
		
		<h2>Changelog</h2>
		<?php
		foreach ($infoUpdate as $data) {
		?>
			<div class="update-data">
				<div><b><?= $data['version'] ?></b></div>
				<div><?= nl2br($data['changelog']) ?></div>
			</div>
		<?php
		}
	} else {
	?>
		<div>Your app is up to date!</div>
	<?php
	}
	?>
</div>

<?php
if (isset($session['dataUpdate'])) {
?>
	<script type="text/javascript">
		var progress = 0;
		var counter = 0;
		var processing = false;
		var dataUpdate = JSON.parse('<?= json_encode($dataUpdate) ?>');
		var totalData = dataUpdate.length;

		function processUpdate(data) {
			console.log('begin update to version '+data.version);
			var iconId = '#icon' + data.version.replace(/\./g, '-');
			if (!$(iconId).hasClass('fa-spinner')) {
				$(iconId).removeClass('fa-square-o');
				$(iconId).addClass('fa-spinner fa-pulse');
			}

			$.ajax({
				url: '<?= Url::to(['update/update']); ?>',
				data: {data: data},
				method: 'POST',
				success: function(result) {
					if (result == 'success') {
						progress += 100 / totalData;
						$(iconId).removeClass('fa-spinner fa-pulse');
						$(iconId).addClass('fa-check-square-o');
					} else {
						console.log(result);
					}
					if (counter == totalData)
						progress = 100;
					$('.progress-bar').css('width', progress+'%').attr('aria-valuenow', progress);

					console.log(result);
				},
				complete: function() {
					if (counter < totalData) {
						counter++;
						processUpdate(dataUpdate[counter-1]);
					} else {
						$('.modal').modal('show');
					}
				}
			});
		}

		$('.start-update').click(function() {
			if (!processing) {
				processing = true;
				if (counter < totalData) {
					counter++;
					processUpdate(dataUpdate[counter-1]);
				}
			}
		});

		$('.btn-close').click(function() {
			$('.modal').modal('hide');
		});
	</script>
<?php
}
?>