<?php
require_once('lti.php');
require_once('resource_base.php');
class scores extends resource_base
{
    /**
     * Class constructor.
     *
     * @param gradebookservices $service Service instance
     */
    public function __construct($service)
    {
        parent::__construct($service);
        $this->id = 'Score.collection';
        $this->template = '/{offeringid_contentdtlid}/lineitems/{item_id}/lineitem/scores';
        $this->variables[] = 'Scores.url';
        $this->formats[] = 'application/vnd.ims.lis.v1.scorecontainer+json';
        $this->formats[] = 'application/vnd.ims.lis.v1.score+json';
        $this->methods[] = 'POST';
    }

    /**
     * Execute the request for this resource.
     *
     * @param response $response  Response object for this request.
     */
    public function execute($response, $date_time)
    {
        $lti = new LTI();
        $params = $this->parse_template();

        $ids = $params['offeringid_contentdtlid'];
        $parts = explode('_', $ids);
        $offering_id = $parts[0];
        $contentdtl_id = $parts[1];
        $grade_item_id = $params['item_id'];

        $json = '[]';
        $body = $response->get_request_data();
        $score = json_decode($body);
        $result_is_null = $lti->check_offering_is_null($offering_id, $score->userId);
        if ($result_is_null->rowCount() > 0) {

            // GET is disabled by the moment, but we have the code ready
            // for a future implementation.
            $isget = $response->get_request_method() === 'GET';
            if ($isget) {
                $contenttype = $response->get_accept();
            } else {
                $contenttype = $response->get_content_type();
            }

            $container = empty($contenttype) || ($contenttype === $this->formats[0]);
            // We will receive typeid when working with LTI 1.x(1.3 also included), if not the we are in LTI 2.
            $typeid = $_GET['type_id'];

            $scope = gradebookservices::SCOPE_GRADEBOOKSERVICES_SCORE;
            try {
                //Tip: Not implemented in this version, next version
                // if (!$this->check_tool($typeid, $response->get_request_data(), array($scope))) {
                //     throw new \Exception(null, 401);
                // }
                if (
                    empty($ids) || !($container ^ ($response->get_request_method() === self::HTTP_POST)) ||
                    (!empty($contenttype) && !in_array($contenttype, $this->formats))
                ) {
                    throw new \Exception('No context or unsupported content type', 400);
                }

                $course_offer = $lti->check_offering_exists($offering_id);
                if ($course_offer->rowCount() == 0) {
                    throw new \Exception("Not Found: Course Offering {$offering_id} doesn't exist", 404);
                }

                $grade_item = $lti->get_grade_item($grade_item_id);
                if ($grade_item->rowCount() == 0) {
                    throw new \Exception("Not Found: Grade item {$grade_item_id} doesn't exist", 404);
                }

                $item = $this->get_service()->get_lineitem($offering_id, $contentdtl_id, $grade_item_id, $typeid); //offering,grade_items,lti_types
                if ($item === false) {
                    throw new \Exception('Line item does not exist', 404);
                }
                $ltilinkid = null;
                if (isset($item->lti_id)) {
                    $ltilinkid = $item->lti_id;
                }
                if ($ltilinkid != null) {
                    if (is_null($typeid)) {
                        //Tool Proxy not implemented
                    } else {
                        if (isset($item->lti_id) && (!gradebookservices::check_lti_1x_id($ltilinkid, $contentdtl_id, $typeid))) {
                            $response->set_code(403);
                            $response->set_reason("Invalid LTI id supplied.");
                            return;
                        }
                    }
                }
                
                switch ($response->get_request_method()) {
                    case 'GET':
                        $response->set_code(405);
                        $response->set_reason("GET requests are not allowed.");
                        break;
                    case 'POST':
                        try {
                            $json = $this->get_json_for_post_request(
                                $response,
                                $response->get_request_data(),
                                $item,
                                $offering_id,
                                $contentdtl_id,
                                $typeid,
                                $date_time
                            );
                            $response->set_content_type($this->formats[1]);
                        } catch (\Exception $e) {
                            $response->set_code($e->getCode());
                            $response->set_reason($e->getMessage());
                        }
                        break;
                    default: // Should not be possible.
                        $response->set_code(405);
                        $response->set_reason("Invalid request method specified.");
                        return;
                }
                $response->set_body($json);
            } catch (\Exception $e) {
                $response->set_code($e->getCode());
                $response->set_reason($e->getMessage());
            }
        } else {
            $response->set_code(200);
            $response->set_content_type($this->formats[1]);
            $response->set_body($json);
        }
    }

    /**
     * Generate the JSON for a POST request.
     *
     * @param response $response Response object for this request.
     * @param string $body POST body
     * @param object $item Grade item instance
     * @param string $contextid
     * @param string $typeid
     *
     * @throws \Exception
     */
    private function get_json_for_post_request($response, $body, $item, $offering_id, $contentdtl_id, $typeid, $date_time)
    {
        $lti = new LTI();
        $score = json_decode($body);
        if (
            empty($score) ||
            !isset($score->userId) ||
            !isset($score->timestamp) ||
            !isset($score->gradingProgress) ||
            !isset($score->activityProgress)
        ) {
            throw new \Exception('Incorrect score received' . $body, 400);
        }

        $timestamp = strtotime($score->timestamp);
        $score->timestamp = date('Y-m-d H:i:s', $timestamp);

        if (!isset($score->scoreMaximum)) {
            $score->scoreMaximum = 1;
        }
        $response->set_code(200);
        $grade = $lti->get_grade_grades($item->grade_items_id, $offering_id, $score->userId);
        if ($result = $grade->fetch(PDO::FETCH_ASSOC)) {
            //Tip: Cross check last updated_ts - need to check in next version
            // if (!empty($result['last_updated_ts'])) {
            //     if ($result['last_updated_ts'] >= strtotime($score->timestamp)) {
            //         $exmsg = "Refusing score with an earlier timestamp for item " . $item->grade_items_id . " and user " . $score->userId;
            //         throw new \Exception($exmsg, 409);
            //     }
            // }
        }
        if (isset($score->scoreGiven)) {
            if ($score->gradingProgress != 'FullyGraded') {
                $score->scoreGiven = null;
            }
        }

        $this->get_service()->save_grade_item($item, $score, $score->userId, $offering_id, $contentdtl_id, $date_time);
    }

    /**
     * Parse a value for custom parameter substitution variables.
     *
     * @param string $value String to be parsed
     *
     * @return string
     */
    public function parse_value($value, $offering_id, $contentdtl_id)
    {
        $lti = new LTI();
        if (strpos($value, '$Scores.url') !== false) {

            $this->params['offeringid_contentdtlid'] = $offering_id . "_" . $contentdtl_id;
            $resolved = '';
            if (!empty($contentdtl_id)) {
                $lti_id = "";
                $grade_items_id = "";
                $lti_class_record = $lti->get_lti($contentdtl_id);
                if ($result = $lti_class_record->fetch(PDO::FETCH_ASSOC)) {
                    $lti_id = $result['lti_id'];
                }
                $grade_items_record = $lti->get_grade_items($contentdtl_id, $lti_id);
                if ($result = $grade_items_record->fetch(PDO::FETCH_ASSOC)) {
                    $grade_items_id = $result['grade_items_id'];
                }
                $this->params['item_id'] = $grade_items_id;
                $resolved = parent::get_endpoint();
            }
            $value = str_replace('$Scores.url', $resolved, $value);
        }
        return $value;
    }
}

