<?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 completion {
    public const FAILED = -1;
    public const INCOMPLETE = 0;
    public const PENDING = 1;
    public const PROGRESS = 2;
    public const COMPLETED = 3;
    public const GOOD = 4;
    public const EXCELLENT = 5;

    private const LABELS = [
        self::FAILED     => 'failed',
        self::INCOMPLETE => 'incomplete',
        self::PENDING    => 'pending',
        self::PROGRESS   => 'progress',
        self::COMPLETED  => 'completed',
        self::GOOD       => 'good',
        self::EXCELLENT  => 'excellent',
    ];

    public static function label($completion) {
        if (array_key_exists($completion, self::LABELS)) {
            return self::LABELS[$completion];
        } else {
            return self::LABELS[self::INCOMPLETE];
        }
    }

    public static function structure($value=VALUE_REQUIRED) {
        return new \external_value(PARAM_TEXT, 'completion state (failed|incomplete|pending|progress|completed|good|excellent)', $value);
    }

    public static function count_states(array $states) {
        // Initialize result array.
        $statecount = [];
        foreach (array_keys(self::LABELS) as $key) {
            $statecount[$key] = 0;
        }

        // Process all states in array and increment relevant counter for each one.
        foreach ($states as $c) {
            if (array_key_exists($c, $statecount)) {
                $statecount[$c] += 1;
            }
        }

        return $statecount;
    }

}