<?php

/**
 * Class Decommissioned_hosts_model
 */
class Decommissioned_hosts_model extends Cf_Model
{
    private $from;
    private $to;
    private $period;

    public const DEFAULT_PERIOD = 'week';

    /**
     * @var array
     */
    private static $periodsMap = [
        'day' => ['postgresFormat' => 'dd Mon yyyy', 'phpFormat' => 'd M Y'],
        'week' => ['postgresFormat' => '"Week #"WW yyyy', 'phpFormat' => '\W\e\e\k #W Y'],
        'month' => ['postgresFormat' => 'Mon yyyy', 'phpFormat' => 'M Y'],
        'year' => ['postgresFormat' => 'yyyy', 'phpFormat' => 'Y'],
    ];

    /**
     * @param $from
     * @param $to
     * @param string $period
     *
     * @return array
     */
    public function getDecommissionedHostCount($from, $to, $period = self::DEFAULT_PERIOD)
    {
        $this->from = $from;
        $this->to = $to;
        $this->period = strtolower($period);

        $where = [
            'time >' => "{$this->from}",
            'time <' => "{$this->to}",
            'item_type' => 'host',
            'message like' => '%decommissioned%',
        ];

        $result = $this->db
            ->select(
                "COUNT(*) as count, to_char(time , '" .
                    self::$periodsMap[$this->period]['postgresFormat'] .
                    "' ) as period",
            )
            ->where($where)
            ->group_by('period')
            ->get('eventslog')
            ->result_array();
        $combinedResult = $this->combinePeriods($result);
        return ['period' => $this->period, 'data' => $this->decorateResponse($combinedResult)];
    }

    /**
     * @param $periods
     *
     * @return array
     */
    private function decorateResponse($periods)
    {
        $data = [];
        foreach ($periods as $date => $count) {
            $data[] = ['date' => $date, 'count' => $count];
        }
        return $data;
    }

    /**
     * @param $periodWithData
     *
     * @return array
     */
    private function combinePeriods($periodWithData)
    {
        $defaultPeriods = $this->preparePeriod();
        foreach ($periodWithData as $value) {
            $defaultPeriods[$value['period']] = $value['count'];
        }
        return $defaultPeriods;
    }

    /**
     * @return array
     * @throws Exception
     */
    private function preparePeriod()
    {
        $period = new DatePeriod(new DateTime($this->from), new DateInterval('P1D'), new DateTime($this->to));
        $periods = [];
        foreach ($period as $date) {
            $periods[$date->format(self::$periodsMap[$this->period]['phpFormat'])] = 0;
        }
        return $periods;
    }
}
