<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\View;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
 
      protected $API_URL;
 
	private function getDataFromFileAndConvert($file, $path, $class, $maxItems = 0) 
	{
		$data = json_decode(Storage::disk('local')->get($file));
		foreach($path as $subobject) { $data = $data->$subobject; }
		$items = [];
		foreach($data as $item_data) 
		{
			$items[] = new $class($item_data);
			if($maxItems && count($items) == $maxItems) { break; }
		}

		return $items;
	}

    public function __construct()
    {
		View::share('apiUrl', $this->API_URL = env('API_URL', 'http://api.6fm.nl/'));
		View::share('imgBase', env('IMAGE_BASE_URL', '/'));
		//View::share('onAir', file_get_contents(url('onair')));
		View::composer('widgets.laatstenieuws', function($view) {
			$view->with('data', $this->getDataFromFileAndConvert('laatste_nieuws.json', ['news'], '\Model\NewsItem'));
		});
		View::composer('widgets.populairnieuws', function($view) {
			$view->with('data', $this->getDataFromFileAndConvert('populair_nieuws.json', [], '\Model\NewsItem'));
		});
		View::composer('widgets.nustraks', function($view) {
			$data = json_decode(Storage::disk('local')->get('nu_straks.json'))->schedule;
			$programs = [];
			foreach($data as $item_data) 
			{
				$programs[] = $program = new \Model\Program($item_data->program);
				$program->start = new \DateTimeImmutable($item_data->start->date, new \DateTimeZone($item_data->start->timezone));
				$program->end = new \DateTimeImmutable($item_data->end->date, new \DateTimeZone($item_data->end->timezone));
			}


			$view->with('data', $programs);
		});
		View::composer('widgets.laatstepodcasts', function($view) {
			$view->with('data', $this->getDataFromFileAndConvert('laatste_podcasts.json', ['podcasts'], '\Model\Podcast'));
		});
		View::composer('widgets.menu', function($view) {
			$view->with('news', $this->getDataFromFileAndConvert('laatste_nieuws.json', ['news'], '\Model\NewsItem'))
				->with('popular', $this->getDataFromFileAndConvert('populair_nieuws.json', [], '\Model\NewsItem', 3))
				->with('podcasts', $this->getDataFromFileAndConvert('laatste_podcasts.json', ['podcasts'], '\Model\Podcast'));
		});
    }
 
    protected function registerView(Request $request, $type, $id)
    {
	if(config('app.debug')) {	
        	return;
	}

        app('db')->insert('INSERT INTO `pagestats`(`type`, `item_id`, `visitor_ip`, `session`, `referer`) VALUES(:type, :id, :ip, :session, :referer)', [
            'type' => $type,
            'id' => $id,
            'ip' => $request->server('REMOTE_ADDR'),
            'session' => md5(Session::getId()),
            'referer' => $request->server('HTTP_REFERRER')
        ]);
    }

    protected function API($url)
    {
        return json_decode(file_get_contents($this->API_URL . $url));
    }

    protected static function JsonToDateTime($obj) 
    {
        return new \DateTime($obj->date, new \DateTimeZone($obj->timezone));
    }

}
