<?php
/**
 * Command Line Interface class: Quota Cop
 *
 * Done for Palas GmbH
 *
 * $Id$
 *
 * @author gERD Schaufelberger <gerd@php-tools.net>
 * @package WB
 * @subpackage palas
 */

WBClass::load( 'WBCli'
    , 'WBObserver');

/**
 * Command Line Interface class: Quota Cop
 *
 * Done for Palas GmbH
 *
 * @version 0.1.0
 * @package WB
 * @subpackage palas
 */
class WBCli_Holiday extends WBCli
{
    /**
     * @var WBDatasource_Holiday
     */
    private $holiday;

    /**
     * Command line arguments
     * @var array
     */
    protected $arguments  =   array(
            CONSOLE_GETARGS_PARAMS  =>  array(
                        'min'       =>  1,
                        'max'       =>  -1,
                        'default'   =>  '',
                        'desc'      =>  'date',
                    )
    );

    /**
     * 2nd constructor
     *
     * Load event processor
     *
     * @see include/WB/WBCli#init()
     */
    protected function init()
    {
        $this->holiday  =   WBClass::create('WBDatasource_Holiday');
    }

    /**
     * execute programme
     *
     * Use observer and execute event queue
     */
    protected function execute()
    {
        if (empty($this->commands)) {
            $this->commands =   array('now');
        }

        $region =   'BW';

        foreach ($this->commands as $c) {
            $this->updateYear($c, $region);
        }

    }

    private function updateYear($date, $region)
    {
        $year   =   date('Y', strtotime($date));
        $this->pl('year ' . $year);

        $url    =   'https://feiertage-api.de/api/?jahr=%d&nur_land=%s';
        $url    =   sprintf($url, $year, $region);
        $cnt    =   file_get_contents($url);

        $list   =   json_decode($cnt, true);
        foreach ($list as $t => $l) {
            $data   =   array(
                                'title'     =>  $t,
                                'holiday'   =>  $l['datum'],
                                'brief'     =>  $l['hinweis'],
                                'country'   =>  'de',
                                'region'    =>  'BW'
                            );
            $id =   $this->holiday->save($data);
            $this->pvl($id . "\t" . $t);
        }
    }
}