<?php
// This file is part of the Studyplan plugin for Moodle
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <https://www.gnu.org/licenses/>.
/**
 *
 * @package    local_treestudyplan
 * @copyright  2023 P.M. Kuipers
 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

namespace local_treestudyplan;

require_once($CFG->libdir.'/externallib.php');

class period {
    const TABLE = "local_treestudyplan_period";
    private static $CACHE = [];
    private static $PAGECACHE = [];


    private $r; // Holds database record.
    private $id;
    private $page;

    public function aggregator() {
        return $this->studyplan->aggregator();
    }

    // Cache constructors to avoid multiple creation events in one session.
    public static function findById($id): self {
        if (!array_key_exists($id, self::$CACHE)) {
            self::$CACHE[$id] = new self($id);
        }
        return self::$CACHE[$id];
    }

    /**
     * Find a period by page and period number [1..$page->periods()]
     */
    public static function find(studyplanpage $page, $periodnr): self{
        global $DB;
        if ($periodnr < 1) {
            // Clamp period index .
            $periodnr = 1;
        }
        try {
            $id = $DB->get_field(self::TABLE, "id", ["page_id"=>$page->id(), "period" => $periodnr], MUST_EXIST);
            $period = self::findById($id);
        } catch(\dml_missing_record_exception $x) {
            // Period does not exist - create one ...
            // Make a best guess estimate of the start and end date, based on surrounding periods,.
            // Or specified duration of the page and the sequence of the periods .
            $pcount = $page->periods();
            $ystart = $page->startdate()->getTimestamp();
            $yend = $page->enddate()->getTimestamp();

            // Estimate the period's timing to make a reasonable first guess.
            $ydelta = $yend - $ystart;
            $ptime = $ydelta / $pcount;

            try {
                 // Check if we have a previous period to glance the end date of as a reference.
                $startdate = $DB->get_field(self::TABLE, "enddate", ["page_id"=>$page->id(), "period" => $periodnr-1], MUST_EXIST);
                $pstart = strtotime($startdate)+(24*60*60); // Add one day.
            } catch(\dml_missing_record_exception $x2) {
                // If not, do a fair guess.
                $pstart = $ystart + (($periodnr-1)*$ptime);
            }
            try {
                // Check if we have a next period to glance the start date of as a reference.
               $enddate = $DB->get_field(self::TABLE, "startdate", ["page_id"=>$page->id(), "period" => $periodnr+1], MUST_EXIST);
               $pstart = strtotime($enddate)-(24*60*60); // subtract one day.
           } catch(\dml_missing_record_exception $x2) {
               // If not, do a fair guess.
                $pend = $pstart + $ptime;
            }

            // And create the period.
            $period = self::add([
                'page_id' => $page->id(),
                'period' => $periodnr,
                'fullname' => \get_string("period_default_fullname", "local_treestudyplan", $periodnr),
                'shortname' => \get_string("period_default_shortname", "local_treestudyplan", $periodnr),
                'startdate' => date("Y-m-d", $pstart),
                'enddate' => date("Y-m-d", $pend),
            ]);
        }
        return $period;
    }

    // Cache constructors to avoid multiple creation events in one session.
    public static function findForPage(studyplanpage $page): array {
        if (!array_key_exists($page->id(), self::$PAGECACHE)) {
            $periods = [];
            // Find and add the periods to an array with the period sequence as a key.
            for($i=1; $i <= $page->periods(); $i++) {
                $period = self::find($page, $i);
                $periods[$i] = $period;
            }
            self::$PAGECACHE[$page->id()] = $periods;
        }
        return self::$PAGECACHE[$page->id()];
    }

    private function __construct($id) {
        global $DB;
        $this->id = $id;
        $this->r = $DB->get_record(self::TABLE, ['id' => $id]);
        $this->page = studyplanpage::findById($this->r->page_id);
    }

    public function id() {
        return $this->id;
    }

    public function studyplan() : studyplan {
        return $this->page->studyplan();
    }

    public function page() {
        return $this->page;
    }

    public function shortname() {
        return $this->r->shortname;
    }

    public function fullname() {
        return $this->r->fullname;
    }

    public function period() {
        return $this->r->period;
    }

    public function startdate() {
        return new \DateTime($this->r->startdate);
    }

    public function enddate() {
        if ($this->r->enddate && strlen($this->r->enddate) > 0) {
            return new \DateTime($this->r->enddate);
        } else{
            // Return a date 100 years into the future.
            return (new \DateTime($this->r->startdate))->add(new \DateInterval("P100Y"));
        }
    }

    public static function structure($value=VALUE_REQUIRED) {
        return new \external_single_structure([
            "id" => new \external_value(PARAM_INT, 'id of period'),
            "fullname" => new \external_value(PARAM_TEXT, 'Full name of period'),
            "shortname"=> new \external_value(PARAM_TEXT, 'Short name of period'),
            "period" => new \external_value(PARAM_INT, 'period sequence'),
            "startdate" => new \external_value(PARAM_TEXT, 'start date of period'),
            "enddate" => new \external_value(PARAM_TEXT, 'end date of period'),
        ], 'Period info', $value);
    }

    public function model() {
        return [
            'id' => $this->r->id,
            'fullname' => $this->r->fullname,
            'shortname' => $this->r->shortname,
            'period' => $this->r->period,
            'startdate' => $this->r->startdate,
            'enddate' => $this->r->enddate,
        ];
    }

    /**
     * Do not use directly to add periods, unless performing import
     * The static find() and findForPage() functions create the period if needed
     */
    public static function add($fields) {
        global $DB;

        if (!isset($fields['page_id'])) {
            throw new \InvalidArgumentException("parameter 'page_id' missing");
        }
        if (!isset($fields['period'])) {
            throw new \InvalidArgumentException("parameter 'period' missing");
        }

        if ($DB->record_exists(self::TABLE, ["page_id"=>$fields["page_id"], "period"=>$fields["period"]])) {
            throw new \InvalidArgumentException("record already exists for specified page and period");
        }

        $addable = ['page_id', 'fullname', 'shortname', 'period', 'startdate', 'enddate'];
        $info = [ ];
        foreach ($addable as $f) {
            if (array_key_exists($f, $fields)) {
                $info[$f] = $fields[$f];
            }
        }
        $id = $DB->insert_record(self::TABLE, $info);
        unset(self::$PAGECACHE[$fields['page_id']]); // invalidate the cache for this page.
        return self::findById($id); // make sure the new page is immediately cached.
    }

    public function edit($fields) {
        global $DB;
        $editable = ['fullname', 'shortname', 'startdate', 'enddate'];
        $info = ['id' => $this->id, ];
        foreach ($editable as $f) {
            if (array_key_exists($f, $fields)) {
                $info[$f] = $fields[$f];
            }
        }
        $DB->update_record(self::TABLE, $info);
        //reload record after edit.
        $this->r = $DB->get_record(self::TABLE, ['id' => $this->id], "*", MUST_EXIST);
        unset(self::$PAGECACHE[$this->r->page_id]); // invalidate the cache for this page.
        return $this;
    }

    public function delete() {
        global $DB;
        $DB->delete_records(self::TABLE, ['id' => $this->id]);
        unset(self::$PAGECACHE[$this->r->page_id]); // invalidate the cache for this page.
        return success::success();
    }

    public static function page_structure($value=VALUE_REQUIRED) {
        return new \external_multiple_structure(self::structure(), "The periods in the page", $value);
    }

    public static function page_model(studyplanpage $page) {
        $model = [];
        foreach (self::findForPage($page) as $p) {
            $model[] = $p->model();
        }
        return $model;
    }

}