<?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/>.

/**
 * Model class for period descriptions
 * @package    local_treestudyplan
 * @copyright  2023 P.M. Kuipers
 * @license    https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

namespace local_treestudyplan;

use DateInterval;
use DateMalformedStringException;
use core_external\external_api;
use core_external\external_function_parameters;
use core_external\external_description;
use core_external\external_value;
use core_external\external_multiple_structure;
use core_external\external_single_structure;
use local_treestudyplan\local\helpers\formatter;

defined('MOODLE_INTERNAL') || die();

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

/**
 * Model class for period descriptions
 */
class period {
    /** @var string */
    const TABLE = "local_treestudyplan_period";
    /**
     * Cache all retrieved periods in this session
     * @var array */
    private static $cache = [];

    /**
     * Holds database record
     * @var stdClass
     */
    private $r;
    /** @var int */
    private $id;
    /** @var studyplanpage */
    private $page;

    /**
     * Shortcut to studyplan (page)'s aggregator
     */
    public function aggregator(): aggregator {
        return $this->page->aggregator();
    }

    /**
     * Find record in database and return management object
     * *Caches to avoid multiple creation events in one session.
     * @param int $id Id of database record
     */
    public static function find_by_id($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()]
     * @param studyplanpage $page Studyplan page to find period for
     * @param int $periodnr Period sequence nr [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::find_by_id($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 = ((object)($page->enddate(true)))->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 $x) {
                // If not, do a fair guess.
                $pend = $pstart + $ptime;
            }

            // Continue period numbers if so configured.
            if (get_config("local_treestudyplan", "continueperiodnumberingnewpage")) {
                $offset = 0;
                foreach (studyplanpage::find_studyplan_children($page->studyplan()) as $p) {
                    if ($p->id() != $page->id()) {
                        $offset += $p->periods();
                    }
                }
                $displaynr = $periodnr + $offset;
            } else {
                $displaynr = $periodnr;
            }
            // And create the period.
            $period = self::add([
                'page_id' => $page->id(),
                'period' => $periodnr,
                'fullname' => \get_string("period_default_fullname", "local_treestudyplan", $displaynr),
                'shortname' => \get_string("period_default_shortname", "local_treestudyplan", $displaynr),
                'startdate' => date("Y-m-d", $pstart),
                'enddate' => date("Y-m-d", $pend),
            ]);
        }
        return $period;
    }

    /**
     * Find all periods registered to a studyplan in sequence
     * @param studyplanpage $page Studyplan page to find periods for
     * @return period[]
     */
    public static function find_for_page(studyplanpage $page): array {
        $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;
        }
        return $periods;
    }

    /**
     * Construct new instance from DB record
     * @param int $id Id of database record
     */
    private function __construct($id) {
        global $DB;
        $this->id = $id;
        $this->r = $DB->get_record(self::TABLE, ['id' => $id]);
        $this->page = studyplanpage::find_by_id($this->r->page_id);
    }

    /**
     * Return database identifier
     * @return int
     */
    public function id() {
        return $this->id;
    }

    /**
     * Return associated studyplan
     * @return studyplan
     */
    public function studyplan(): studyplan {
        return $this->page->studyplan();
    }

    /**
     * Return associated studyplan page
     * @return studyplanpage
     */
    public function page() {
        return $this->page;
    }

    /**
     * Return short name
     * @return string
     */
    public function shortname() {
        return $this->r->shortname;
    }

    /**
     * Return full name
     * @return string
     */
    public function fullname() {
        return $this->r->fullname;
    }

    /**
     * Return period sequence number
     * @return int
     */
    public function period() {
        return $this->r->period;
    }

    /**
     * Start date
     * @return \DateTime
     */
    public function startdate() {
        if (strlen($this->r->startdate) > 0) {
            try {
                return new \DateTime($this->r->startdate);
            } catch (\Exception $x) {
                // Fallback - Return start of era if date is malformed.
                return new \DateTime("2010-01-01");
            }
        } else {
                // Fallback - Return start of era if date is empty.
            return new \DateTime("2010-01-01");
        }
    }

    /**
     * End date
     * @return \DateTime
     */
    public function enddate() {
        if (strlen($this->r->enddate) > 0) {
            try {
                return new \DateTime($this->r->enddate);
            } catch (\Exception $x) {
                // Return a date 2 months into the future if malformed.
                // May not be properly set after switch to and from timless mode.
                return ($this->startdate())->add(new \DateInterval("P2M"));
            }
        } else {
            // Return a date 2 months into the future if not set.
            // May not be properly set after switch to and from timless mode.
            return ($this->startdate())->add(new \DateInterval("P2M"));
        }
    }

    /**
     * Webservice structure for basic info
     * @param int $value Webservice requirement constant
     */
    public static function structure($value = VALUE_REQUIRED): external_description {
        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'),
            "display" => new external_single_structure([
                "fullname" => new external_value(PARAM_RAW, 'full name of studyplan period (filtered)'),
                "shortname" => new external_value(PARAM_RAW, 'short name of studyplan period (filtered)'),
            ], "display names with filters applied"),
            "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'),
            "timeless" => new external_value(PARAM_BOOL, 'Page does not include time information'),
        ], 'Period info', $value);
    }

    /**
     * Webservice model for basic info
     * @return array Webservice data model
     */
    public function model() {
        $timeless = boolval(get_config("local_treestudyplan", "timelessperiods"));
        return [
            'id' => $this->r->id,
            'fullname' => $this->r->fullname,
            'shortname' => $this->r->shortname,
            'display' => [
                'fullname' => formatter::format_string($this->r->fullname),
                'shortname' => formatter::format_string($this->r->shortname),
            ],
            'period' => $this->r->period,
            'startdate' => ($timeless) ? "" : $this->startdate()->format("Y-m-d"),
            'enddate' => ($timeless) ? "" : $this->enddate()->format("Y-m-d"),
            'timeless' => $timeless,
        ];
    }

    /**
     * Add a new period for a studyplan page
     * Use only when performing import! The static find() and find_for_page() functions create the period during normal operation
     * @param array $fields Properties for ['page_id', 'fullname', 'shortname', 'period', 'startdate', 'enddate']
     */
    public static function add($fields): self {
        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);
        return self::find_by_id($id); // Make sure the new page is immediately cached.
    }

    /**
     * Edit period properties
     * @param array $fields Properties for ['fullname', 'shortname', 'startdate', 'enddate']
     */
    public function edit($fields): self {
        global $DB;

        $pages = self::find_for_page($this->page());
        $prev = (count($pages) > 2 && $this->period() >= 1) ? $pages[$this->period() - 1] : null;
        $next = (count($pages) > $this->period()) ? $pages[$this->period() + 1] : null;

        $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 and ensure end dates of previous period are adjusted if needed.
        $this->r = $DB->get_record(self::TABLE, ['id' => $this->id], "*", MUST_EXIST);

        // Adjust end date of previous period if needed.
        if (isset($prev) && !empty($fields['startdate'])) {
            $maxdate = $this->startdate()->sub(new DateInterval("P1D")); // Subtract 1 day, since periods include the end day.
            $rqdate = $prev->enddate();
            if ($maxdate < $rqdate) {
                $prev->edit(["enddate" => $maxdate->format("Y-m-d")]);
            }
        }

        // Adjust start date of next period if needed.
        if (isset($next) && !empty($fields['enddate'])) {
            $mindate = $this->enddate()->add(new DateInterval("P1D")); // Subtract 1 day, since periods include the end day.
            $rqdate = $next->startdate();
            if ($mindate > $rqdate) {
                $next->edit(["startdate" => $mindate->format("Y-m-d")]);
            }
        }

        return $this;
    }

    /**
     * Delete period
     */
    public function delete(): success {
        global $DB;
        $DB->delete_records(self::TABLE, ['id' => $this->id]);
        return success::success();
    }

    /**
     * Webservice structure for list of periods in page
     * @param int $value Webservice requirement constant
     */
    public static function page_structure($value = VALUE_REQUIRED): external_description {
        return new external_multiple_structure(self::structure(), "The periods in the page", $value);
    }

    /**
     * Webservice model list of periods in page
     * @param studyplanpage $page The page to create the model for
     * @return array Webservice data model
     */
    public static function page_model(studyplanpage $page): array {
        $model = [];
        foreach (self::find_for_page($page, true) as $p) {
            $model[] = $p->model();
        }
        return $model;
    }
}
