<?php

use Carbon\Carbon;
use Louis1021\ICalendar\helpers\SG_iCal_Query;
use Louis1021\ICalendar\SG_iCalReader;

defined('BASEPATH') or exit('No direct script access allowed');

class Welcome extends CI_Controller
{
  // Hardcoded Calendar Schedule Event Settings
  private $fromTime = '06:00';
  private $toTime = '20:00';

  // Storage
  private $data = [];
  private $dates = [];

  public function index()
  {
    /**
     * Add CSS / JS
     * @see https://www.tutorialspoint.com/codeigniter/codeigniter_adding_js_css.htm
     */
    $this->load->helper('url');

    /**
     * Since read_file is deprecated, use file_get_contents() instead
     * The dot means the current path (root path)
     */
    $content = './uploads/1576452468-tc.ics';

    $calendar = $this->parseICS($content);

    $this->load->view('admin/welcome_message', [
      '_events' => $calendar->json(),
      // resource is a set of labels, the calendar.js will handle it
      '_resources' => json_encode(['Room A', 'Room B', 'Room C', 'Room D', 'Room E', 'Room F']),
    ]);
  }

  protected function parseICS($path, $startdate = null, $enddate = null)
  {
    $ical = new SG_iCalReader($path);
    $query = new SG_iCal_Query();

    $evts = $ical->getEvents();
    //$evts = $query->Between($ical,strtotime('20100901'),strtotime('20101131'));

    $data = array();
    if ($evts) {
      foreach ($evts as $id => $ev) {

        $jsEvt = array(
          "id" => ($id + 1),
          "title" => $ev->getProperty('summary'),
          "start" => $this->getRefinedFromTime($ev->getStart()),
          "end"   => $this->getRefinedToTime($ev->getEnd() - 1),
          "allDay" => $ev->isWholeDay(),
          "category" => "publicholiday"
        );

        if (isset($ev->recurrence)) {
          $count = 0;
          $start = $ev->getStart();
          $freq = $ev->getFrequency();
          if ($freq->firstOccurrence() == $start)
            $this->data[] = $jsEvt;
          $this->dates[] = Carbon::createFromTimestamp($start)->format('Y-m-d');
          while (($next = $freq->nextOccurrence($start)) > 0) {
            if (!$next or $count >= 1000) break;
            $count++;
            $start = $next;
            $jsEvt["start"] = $start;
            $jsEvt["end"] = $start + $ev->getDuration() - 1;

            $evtIsoDate = Carbon::createFromTimestamp($start)->format('Y-m-d');

            if ($startdate && $enddate) {
              if ($startdate >= $evtIsoDate && $evtIsoDate <= $enddate) {
                $this->data[] = $jsEvt;
                $this->dates[] = $evtIsoDate;
              }
            } else {
              $this->data[] = $jsEvt;
              $this->dates[] = $evtIsoDate;
            }
          }
        } else {
          $start = $jsEvt['start'];
          $evtIsoDate = Carbon::createFromTimestamp($start)->format('Y-m-d');

          if ($startdate && $enddate) {
            if ($startdate >= $evtIsoDate && $evtIsoDate <= $enddate) {
              $this->data[] = $jsEvt;
              $this->dates[] = $evtIsoDate;
            }
          } else {
            $this->data[] = $jsEvt;
            $this->dates[] = $evtIsoDate;
          }
        }
      }
    }

    //echo(date('Ymd\n',$data[0][start]));
    //echo(date('Ymd\n',$data[1][start]));
    //dump_t($data);

    return $this;
  }

  protected function addEvent($id, $date, $duration, $resource, $start, $end, $allDay, $category, $content = null)
  {
    $this->data[] = compact('id', 'date', 'duration', 'resource', 'start', 'end', 'allDay', 'category', 'content');
    return $this;
  }

  protected function json()
  {
    $events = json_encode($this->data);

    return $events;
  }

  protected function holidayJson()
  {
    return json_encode($this->dates);
  }

  /**
   * TODO: 
   * fromTime from database
   * 單數 hour 時減一
   *
   * @param int $unixDateTime
   * @return int
   */
  protected function getRefinedFromTime($unixDateTime)
  {
    list($hour, $minute) = explode(':', $this->fromTime);
    return Carbon::createFromTimestamp($unixDateTime)->setTime($hour, $minute)->timestamp;
  }

  /**
   * TODO: 
   * toTime from database
   * 單數 hour 時加一
   *
   * @param int $unixDateTime
   * @return int
   */
  public function getRefinedToTime($unixDateTime)
  {
    list($hour, $minute) = explode(':', $this->toTime);
    return Carbon::createFromTimestamp($unixDateTime)->setTime($hour, $minute)->timestamp - 1;
  }

  /**
   * Index Page for this controller.
   *
   * Maps to the following URL
   * 		http://example.com/index.php/welcome
   *	- or -
   * 		http://example.com/index.php/welcome/index
   *	- or -
   * Since this controller is set as the default controller in
   * config/routes.php, it's displayed at http://example.com/
   *
   * So any other public methods not prefixed with an underscore will
   * map to /index.php/welcome/<method_name>
   * @see https://codeigniter.com/user_guide/general/urls.html
   */
  public function indexOriginal()
  {
    $this->load->view('welcome_message');
  }
}
