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

class ViewSubmissionUtils {

    /**
     * generates a short summary html
     *
     * @param int assignmentid assignment
     * @param int submissionid submission to create a report for
     * @return string html
     */
    public static function generateSummaryHtml(
        int $assignmentid,
        int $submissionid
    ): string {

        //Fetch data.
        $summary = DbUtils::getResultSummaryFromDatabase($assignmentid, $submissionid);
        $html = "";

        //Calculate success rate, if no unknown result states or compilation errors.
        $successrate = "?";
        if ($summary->unknownCount() == 0 && $summary->compilationErrorCount() == 0) {
            $successrate = round(($summary->successfulCount() / $summary->resultCount()) * 100, 2 );
        }

        //Generate html.
        $html .= $summary->successfulCount() . "/";
        $html .= ($summary->compilationErrorCount() == 0 && $summary->unknownCount() == 0)
            ? $summary->resultCount() . " (" . $successrate . "%)"
                : "?";
        $html .= " tests successful<br>";

        if ($summary->compilationErrorCount() > 0) {
            $html .= $summary->compilationErrorCount() . " compilation error(s)<br>";
        }

        if ($summary->unknownCount() > 0) {
            $html .= $summary->unknownCount() . " test(s) with unknown state<br>";
        }
		
		$html .= $summary->successfulTestCompetencyProfile . " successfully tested competency profile<br>";

        return html_writer::div($html, "dtaSubmissionSummary");
    }

    /**
     * generates detailed view html
     *
     * @param int assignmentid assignment
     * @param int submissionid submission to create a report for
     */
    public static function generateDetailHtml(
        int $assignmentid,
        int $submissionid
    ): string {

        //Fetch data.
        $summary = DbUtils::getResultSummaryFromDatabase($assignmentid, $submissionid);
        $html = "";

        //Define a few css classes and prepare html attribute arrays to beautify the output.
        $tableheaderrow_attributes = array("class" => "dtaTableHeaderRow");
        $tablerow_attributes = array("class" => "dtaTableRow");
        $resultrow_attributes = $tablerow_attributes;
        $unknown_attributes = 'dtaResultUnknown';
        $success_attributes = 'dtaResultSuccess';
        $failure_attributes = 'dtaResultFailure';
        $compilationerror_attributes = 'dtaResultCompilationError';

        //Summary table.
        $tmp = "";
        $tmp .= html_writer::tag("th", "Summary", array("class" => "dtaTableHeader"));
        $tmp .= html_writer::empty_tag("th", array("class" => "dtaTableHeader"));
        $header = html_writer::tag("tr", $tmp, $tableheaderrow_attributes);
        $header = html_writer::tag("thead", $header);

        $body = "";
        $tmp = "";
        $attributes = array("class" => "dtaTableData");
        $tmp .= html_writer::tag(
            "td",
            "result items in sum",
            $attributes);

        $tmp .= html_writer::tag(
            "td",
            $summary->resultCount(),
            $attributes);

        $resultrow_attributes = $tablerow_attributes;
        $resultrow_attributes['class'] = $resultrow_attributes['class'] . " " . $unknown_attributes;
        
        $body .= html_writer::tag("tr", $tmp, $resultrow_attributes);

        $tmp = "";
        $tmp .= html_writer::tag("td", "successes", $attributes);
        $tmp .= html_writer::tag( "td", $summary->successfulCount(), $attributes);

        $resultrow_attributes = $tablerow_attributes;
        $successrate = "?";

        if ($summary->unknownCount() > 0 || $summary->compilationErrorCount() > 0) {
            $resultrow_attributes['class'] = $resultrow_attributes['class'] . " " . $unknown_attributes;
        } else {
            $successrate = round(($summary->successfulCount() / $summary->resultCount()) * 100, 2 );
            if ($successrate < 50) {
                $resultrow_attributes['class'] = $resultrow_attributes['class'] . " " . $compilationerror_attributes;
            } else if ($successrate < 75) {
                $resultrow_attributes['class'] = $resultrow_attributes['class'] . " " . $failure_attributes;
            } else {
                $resultrow_attributes['class'] = $resultrow_attributes['class'] . " " . $success_attributes;
            }
        }
        $body .= html_writer::tag("tr", $tmp, $resultrow_attributes);

        $tmp = "";
        $tmp .= html_writer::tag("td", "failures", $attributes);
        $tmp .= html_writer::tag("td", $summary->failedCount(), $attributes);

        $resultrow_attributes = $tablerow_attributes;
        if ($summary->failedCount() > 0) {
            $resultrow_attributes['class'] = $resultrow_attributes['class'] . " " . $failure_attributes;
        } else {
            $resultrow_attributes['class'] = $resultrow_attributes['class'] . " " . $success_attributes;
        }
        $body .= html_writer::tag("tr", $tmp, $resultrow_attributes);

        $tmp = "";
        $tmp .= html_writer::tag("td", "compilation errors", $attributes);
        $tmp .= html_writer::tag("td", $summary->compilationErrorCount(), $attributes);

        $resultrow_attributes = $tablerow_attributes;
        if ($summary->compilationErrorCount() > 0) {
            $resultrow_attributes['class'] = $resultrow_attributes['class'] . " " . $compilationerror_attributes;
        } else {
            $resultrow_attributes['class'] = $resultrow_attributes['class'] . " " . $success_attributes;
        }
        $body .= html_writer::tag("tr", $tmp, $resultrow_attributes);

        $tmp = "";
        $tmp .= html_writer::tag("td", "unknown state", $attributes);
        $tmp .= html_writer::tag("td", $summary->unknownCount(), $attributes);

        $resultrow_attributes = $tablerow_attributes;
        if ($summary->unknownCount() > 0) {
            $resultrow_attributes['class'] = $resultrow_attributes['class'] . " " . $unknown_attributes;
        } else {
            $resultrow_attributes['class'] = $resultrow_attributes['class'] . " " . $success_attributes;
        }
        $body .= html_writer::tag("tr", $tmp, $resultrow_attributes);

        $tmp = "";
        $tmp .= html_writer::tag("td", html_writer::tag("b","success rate"), $attributes);
        $tmp .= html_writer::tag(
            "td",
            html_writer::tag("b", $summary->successfulCount()
                . "/" . (($summary->compilationErrorCount() == 0 && $summary->unknownCount() == 0) ? $summary->resultCount()
                . " (" . $successrate . "%)"
                    : "?")),
            $attributes);

        $resultrow_attributes = $tablerow_attributes;
        if ($summary->unknownCount() > 0 || $summary->compilationErrorCount() > 0) {
            $resultrow_attributes['class'] = $resultrow_attributes['class'] . " " . $unknown_attributes;
        } else {
            if ($successrate < 50) {
                $resultrow_attributes['class'] = $resultrow_attributes['class'] . " " . $compilationerror_attributes;
            } else if ($successrate < 75) {
                $resultrow_attributes['class'] = $resultrow_attributes['class'] . " " . $failure_attributes;
            } else {
                $resultrow_attributes['class'] = $resultrow_attributes['class'] . " " . $success_attributes;
            }
        }
        $body .= html_writer::tag("tr", $tmp, $resultrow_attributes);

        $body = html_writer::tag("tbody", $body);
        $table = html_writer::tag("table", $header . $body, array("class" => "dtaTable"));

        $html .= $table;

        //Add empty div for spacing between summary and details table.
        $html .= html_writer::empty_tag("div", array("class" => "dtaSpacer"));

        //Details table.
        $tmp = "";
        $tmp .= html_writer::tag("th", "Details", array("class" => "dtaTableHeader"));
        $tmp .= html_writer::empty_tag("th", array("class" => "dtaTableHeader"));
        $header = html_writer::tag("tr", $tmp, $tableheaderrow_attributes);
        $header = html_writer::tag("thead", $header);

        $body = "";
        $spacerrow = null;
        foreach($summary->results as $r) {
            //Add spacer first if not null.
            if (!is_null($spacerrow)) {
                $body .= $spacerrow;
            }

            //New copy of base attributes array.
            $resultrow_attributes = $tablerow_attributes;

            //Check which css class to add for the colored left-border according to resuls state.
            if ($r->state == 0) {
                $resultrow_attributes['class'] = $resultrow_attributes['class'] . ' dtaResultUnknown';
            } else if ($r->state == 1) {
                $resultrow_attributes['class'] = $resultrow_attributes['class'] . ' dtaResultSuccess';
            } else if ($r->state == 2) {
                $resultrow_attributes['class'] = $resultrow_attributes['class'] . ' dtaResultFailure';
            } else if ($r->state == 3) {
                $resultrow_attributes['class'] = $resultrow_attributes['class'] . ' dtaResultCompilationError';
            }

            $tmp = "";
            $tmp .= html_writer::tag(
                "td",
                "name",
                $attributes);

            $tmp .= html_writer::tag(
                "td",
                $r->name,
                $attributes);
            $body .= html_writer::tag("tr", $tmp, $resultrow_attributes);

            $tmp = "";
            $tmp .= html_writer::tag(
                "td",
                "state",
                $attributes);

            $tmp .= html_writer::tag(
                "td",
                DtaResult::getStateName($r->state),
                $attributes);
            $body .= html_writer::tag("tr", $tmp, $resultrow_attributes);

            //If state is something different than successful, show additional rows.
            if ($r->state != 1) {
                $tmp = "";
                $tmp .= html_writer::tag(
                    "td",
                    "failure type",
                    $attributes);
        
                $tmp .= html_writer::tag(
                    "td",
                    $r->failureType,
                    $attributes);
                $body .= html_writer::tag("tr", $tmp, $resultrow_attributes);

                $tmp = "";
                $tmp .= html_writer::tag(
                    "td",
                    "failure reason",
                    $attributes);

                $tmp .= html_writer::tag(
                    "td",
                    $r->failureReason,
                    $attributes);
                $body .= html_writer::tag("tr", $tmp, $resultrow_attributes);

                //Only show line, column and position if they have useful values.
                if (!is_null($r->lineNumber) && $r->lineNumber > 0) {
                    $tmp = "";
                    $tmp .= html_writer::tag(
                        "td",
                        "line number",
                        $attributes);

                    $tmp .= html_writer::tag(
                        "td",
                        $r->lineNumber,
                        $attributes);
                    $body .= html_writer::tag("tr", $tmp, $resultrow_attributes);
                }

                if (!is_null($r->columnNumber) && $r->columnNumber > 0) {
                $tmp = "";
                $tmp .= html_writer::tag(
                    "td",
                    "column number",
                    $attributes);

                $tmp .= html_writer::tag(
                    "td",
                    $r->columnNumber,
                    $attributes);
                $body .= html_writer::tag("tr", $tmp, $resultrow_attributes);
                }

                if (!is_null($r->position) && $r->position > 0) {
                $tmp = "";
                $tmp .= html_writer::tag(
                    "td",
                    "position",
                    $attributes);

                $tmp .= html_writer::tag(
                    "td",
                    $r->position,
                    $attributes);
                $body .= html_writer::tag("tr", $tmp, $resultrow_attributes);
                }

                $tmp = "";
                $tmp .= html_writer::tag(
                    "td",
                    "stacktrace",
                    $attributes);

                $tmp .= html_writer::tag(
                    "td",
                    html_writer::tag("details", $r->stacktrace, array("class" => "dtaStacktraceDetails")),
                    $attributes);
                $body .= html_writer::tag("tr", $tmp, $resultrow_attributes);
            }

            //Set spacerrow value if null for next rount separation.
            if (is_null($spacerrow)) {
                $spacerrow = html_writer::empty_tag("tr", array("class" => "dtaTableSpacer"));
            }
        }
        $html .= html_writer::tag("table", $header . $body, array("class" => "dtaTable"));

        // wrap generated html into final div
        $html = html_writer::div($html, "dtaSubmissionDetails");

        return $html;
    }

}