<?php

// 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 <http://www.gnu.org/licenses/>.

/**
 * External Web Service Template
 *
 * @package    mod_timetable
 * @copyright  2020 Raphael Dannecker <raphael.dannecker@steinbeisschule-reutlingen.de>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
require_once($CFG->libdir . "/externallib.php");

class mod_timetable_external extends external_api {

    /**
     * Returns description of method parameters
     * @return external_function_parameters
     */
    public static function search_parameters() {
        return new external_function_parameters(
                array('searchstring' => new external_value(PARAM_TEXT, 'The searchstring.', VALUE_DEFAULT, ''))
        );
    }

    /**
     * Returns welcome message
     * @return search result message
     */
    public static function search($searchstring = 'Hello world, ') {
        global $USER,$DB;

        //Parameter validation
        //REQUIRED
        $params = self::validate_parameters(self::search_parameters(),
                array('searchstring' => $searchstring));

        //Context validation
        //OPTIONAL but in most web service it should present
        $context = get_context_instance(CONTEXT_USER, $USER->id);
        self::validate_context($context);

        //Capability checking
        //OPTIONAL but in most web service it should present
        if (!has_capability('mod/timetable:search', $context)) {
            throw new moodle_exception('cannotperformsearch');
        }

        
        $results = array();
        //return $params['searchstring'] . $USER->firstname ;
        $classes = $DB->get_records_select('timetable_class', 'class like ? OR description like ? LIMIT 10', array ('%'.$params['searchstring'].'%', '%'.$params['searchstring'].'%'));
        foreach($classes as $class) {
            $result = array(
                'type' => 'class',
                'name' => $class->class,
                'description' => "Klassenplan: $class->description ($class->class)"
            );
            $results[] = $result;
        }
        $teachers = $DB->get_records_select('timetable_teacher', 'teacher like ? OR surname like ? LIMIT 10', array ('%'.$params['searchstring'].'%', '%'.$params['searchstring'].'%'));
        foreach($teachers as $teacher) {
            $result = array(
                'type' => 'teacher',
                'name' => $teacher->teacher,
                'description' => "Lehrerplan: $teacher->surname, $teacher->firstname ($teacher->teacher)"
            );
            $results[] = $result;
        }
        $rooms = $DB->get_records_select('timetable_room', 'description like ? limit 10', array ('%'.$params['searchstring'].'%'));
        foreach($rooms as $room) {
            $result = array(
                'type' => 'room',
                'name' => $room->room,
                'description' => "Raumplan: ".$room->description
            );
            $results[] = $result;
        }
        //echo var_dump($results);
        return $results;
    }

    /**
     * Returns description of method result value
     * @return external_description
     */
    public static function search_returns() {
        //return new external_value(PARAM_TEXT, 'The search result');
        return new external_multiple_structure(
            new external_single_structure(
                array(
                    'type' => new external_value(PARAM_TEXT, 'type of timetable: class, teacher, room'),
                    'name' => new external_value(PARAM_TEXT, 'value of type'),
                    'description' => new external_value(PARAM_TEXT, 'description')
                )
            )
        );
    }



    /**
     * Returns description of method parameters
     * @return external_function_parameters
     */
    public static function get_parameters() {
        return new external_function_parameters(
            array(
                'type' => new external_value(PARAM_TEXT, 'The type of timetable: class, teacher, room'),
                'name' => new external_value(PARAM_TEXT, 'value of type'),
                'week' => new external_value(PARAM_INT, 'The week of timetable')
            )
        );
    }

    /**
     * Returns welcome message
     * @return get result message
     */
    public static function get($type,$name,$week) {
        global $USER,$DB;

        //Parameter validation
        //REQUIRED

        //echo "Hallo\n";
        $params = self::validate_parameters(self::get_parameters(),
                array('type' => $type, 'name'=> $name, 'week' => $week));

        //Context validation
        //OPTIONAL but in most web service it should present
        $context = get_context_instance(CONTEXT_USER, $USER->id);
        self::validate_context($context);

        //$contextmodule = context_module::instance($cm->id);
        $usercontext = context_user::instance($USER->id);

        //Capability checking
        //OPTIONAL but in most web service it should present
        if (!has_capability('mod/timetable:view'.$params['type'], $usercontext)) {
            //if (!(($params['type'] == 'class') && has_capability('mod/timetable:viewownclass', $usercontext) && ($params['name'] == str_replace('_','/',$USER->department))))
            if (!(($params['type'] == 'class') && ($params['name'] == str_replace('_','/',$USER->department))))
                throw new \moodle_exception('cannotviewtimetable'.$params['type']);
        }

        /*
        if ($USER->department == "Lehrer" || $USER->department == "Lehrer_fvs") {

        } elseif (($params['type'] == 'class') && ($params['name'] == str_replace('_','/',$USER->department))) {

        } else {
            throw new \moodle_exeption('Forbidden');
        }
        */


        //echo "Type: ".$params['type']."\n";
        //echo "Name: ".$params['name']."\n";
        //echo "Week: ".$params['week']."\n";
        if(!($params['week'])) {
            $today = new \DateTime();
            $params['week'] = $today->format("W");
            $dayofweek = $today->format('w');
            if (($dayofweek > 5 + get_config('timetable', 'saturday')) || ($dayofweek == 0)) {
                $params['week']++;
            }
        }

        $ttable = new \mod_timetable\timetable($params['type'],$params['name']);
        $ttable->read_db($params['week']);
        //echo var_dump($ttable->prepare_output());
        return $ttable->prepare_output();
        //$renderable = new \mod_timetable\output\timetable($ttable);
        //return $renderable->export_for_template(new \mod_timetable\output\renderer($USER,array()));
    }

    /**
     * Returns description of method result value
     * @return external_description
     */
    public static function get_returns() {


        return new external_single_structure(
            array(
                'periods' => new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'number' => new external_value(PARAM_INT, 'number of period'),
                            'days' => new external_multiple_structure(
                                new external_single_structure(
                                    array(
                                        'substitution' => new external_value(PARAM_TEXT, 'substitution'),
                                        'lessons' => new external_multiple_structure(
                                            new external_single_structure(
                                                array(
                                                    'class'   => new external_value(PARAM_TEXT, 'name of class'),
                                                    'teacher' => new external_value(PARAM_TEXT, 'name of teacher'),
                                                    'room'    => new external_value(PARAM_TEXT, 'name of room'),
                                                    'subject' => new external_value(PARAM_TEXT, 'name of subject'),
                                                    'status'  => new external_value(PARAM_TEXT, 'status of lesson'),
                                                    'flag'    => new external_value(PARAM_TEXT, 'flag of lesson')
                                                )
                                            )
                                        )
                                    )
                                )
                            )
                        )
                    )
                ),
                'type'        => new external_value(PARAM_TEXT, 'The type of timetable: class, teacher, room'),
                'name'        => new external_value(PARAM_TEXT, 'value of type'),
                'date'        => new external_value(PARAM_TEXT, 'date'),
                'description' => new external_value(PARAM_TEXT, 'description'),
                'saturday'    => new external_value(PARAM_INT, 'if timetable includes saturday'),
                'week'        => new external_value(PARAM_INT, 'The week of timetable'),
                'prevweek'    => new external_value(PARAM_INT, 'The next week of timetable'),
                'nextweek'    => new external_value(PARAM_INT, 'The prev week of timetable'),
                'id'          => new external_value(PARAM_TEXT, 'The id of timetable')
            )
        );
    }

}