<?php
// This file is part of Moodle - http://moodle.org/
//
// 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/>.

/**
 * persistence layer utility class
 *
 * @package assignsubmission_dta
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @copyright Gero Lueckemeyer and student project teams
 */
class DbUtils {

    /**
     * Summary database table name.
     */
    private const TABLE_SUMMARY = "assignsubmission_dta_summary";
    /**
     * Result database table name.
     */
    private const TABLE_RESULT = "assignsubmission_dta_result";

    /**
     * gets summary with all corresponding result entries
     *
     * @param int $assignmentid assignment id to search for
     * @param int $submissionid submission id to search for
     * @return DttResultSummary representing given submission
     */
    public static function getresultsummaryfromdatabase(
        int $assignmentid,
        int $submissionid
    ): DtaResultSummary {
        global $DB;

        // Fetch data from database.
        $summaryrecord = $DB->get_record(self::TABLE_SUMMARY, [
            "assignment_id" => $assignmentid,
            "submission_id" => $submissionid,
        ]);

        $resultsarray = $DB->get_records(self::TABLE_RESULT, [
            "assignment_id" => $assignmentid,
            "submission_id" => $submissionid,
        ]);

        // Create a summary instance.
        $summary = new DtaResultSummary();
        $summary->timestamp = $summaryrecord->timestamp;
        $summary->globalstacktrace = $summaryrecord->global_stacktrace;
        $summary->successfultestcompetencies = $summaryrecord->successful_competencies;
        $summary->overalltestcompetencies = $summaryrecord->tested_competencies;
        $summary->results = [];

        // Create result instances and add to array of summary instance.
        foreach ($resultsarray as $rr) {
            $result = new DtaResult();
            $result->packagename = $rr->package_name;
            $result->classname = $rr->class_name;
            $result->name = $rr->name;
            $result->state = $rr->state;
            $result->failuretype = $rr->failure_type;
            $result->failurereason = $rr->failure_reason;
            $result->stacktrace = $rr->stacktrace;
            $result->columnnumber = $rr->column_number;
            $result->linenumber = $rr->line_number;
            $result->position = $rr->position;

            $summary->results[] = $result;
        }

        return $summary;
    }

    /**
     * save given result summary and single results to database
     * under given assignment and submission id
     *
     * @param int $assignmentid assigment this is submission is linked to
     * @param int $submissionid submission of this result
     * @param DtaResultSummary $summary instance to persist
     */
    public static function storeresultsummarytodatabase(
        int $assignmentid,
        int $submissionid,
        DtaResultSummary $summary
    ): void {
        global $DB;

        // Prepare new database entries.
        $summaryrecord = new stdClass();
        $summaryrecord->assignment_id = $assignmentid;
        $summaryrecord->submission_id = $submissionid;
        $summaryrecord->timestamp = $summary->timestamp;
        $summaryrecord->global_stacktrace = $summary->globalstacktrace;
        $summaryrecord->successful_competencies = $summary->successfultestcompetencies;
        $summaryrecord->tested_competencies = $summary->overalltestcompetencies;

        // Prepare results to persist to array.
        $resultrecords = [];
        foreach ($summary->results as $r) {
            $record = new stdClass();
            $record->assignment_id = $assignmentid;
            $record->submission_id = $submissionid;
            $record->package_name = $r->packagename;
            $record->class_name = $r->classname;
            $record->name = $r->name;
            $record->state = $r->state;
            $record->failure_type = $r->failuretype;
            $record->failure_reason = $r->failurereason;
            $record->stacktrace = $r->stacktrace;
            $record->column_number = $r->columnnumber;
            $record->line_number = $r->linenumber;
            $record->position = $r->position;
            $resultrecords[] = $record;
        }

        // If results already exist, delete old values beforehand.
        $submission = $DB->get_record(self::TABLE_SUMMARY, [
            'assignment_id' => $assignmentid,
            'submission_id' => $submissionid,
        ]);

        if ($submission) {
            $DB->delete_records(self::TABLE_RESULT, [
                'assignment_id' => $assignmentid,
                'submission_id' => $submissionid,
            ]);

            $DB->delete_records(self::TABLE_SUMMARY, [
                'assignment_id' => $assignmentid,
                'submission_id' => $submissionid,
            ]);
        }

        // Create summary and single result entries.
        $DB->insert_record(self::TABLE_SUMMARY, $summaryrecord);
        foreach ($resultrecords as $rr) {
            $DB->insert_record(self::TABLE_RESULT, $rr);
        }
    }

    /**
     * cleans up database if plugin is uninstalled
     */
    public static function uninstallplugincleaup(): void {
        global $DB;

        $DB->delete_records(self::TABLE_RESULT, null);
        $DB->delete_records(self::TABLE_SUMMARY, null);
    }

}