<commit_before>﻿using ChalmersxTools.Models;
using ChalmersxTools.Models.Database;
using ChalmersxTools.Models.View;
using LtiLibrary.Core.Outcomes.v1;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web;

namespace ChalmersxTools.Tools
{
    public class EarthSpheresImageTool : SimpleDataStorageToolBase
    {
        public static readonly string CONSUMER_KEY = "ChalmersxEarthSpheresImageTool";

        public override string ConsumerKey { get { return CONSUMER_KEY; } }
        protected override string ConsumerSecret { get { return ConfigurationManager.AppSettings["ltiConsumerSecret"]; } }

        public override CsvFileData HandleDataRequest()
        {
            string data = "";
            data += "sphere1Name,sphere1Url,sphere2Name,sphere2Url\n";
            foreach (var submission in GetAllSubmissionsForCourseRun())
            {
                data += "\"" + submission.Sphere1Name.Replace('"', '\'').Replace("\r", @"\r").Replace("\n", @"\n") + "\",\"" +
                    submission.Sphere1Url.Replace('"', '\'').Replace("\r", @"\r").Replace("\n", @"\n") + "\",\"" +
                    submission.Sphere2Name.Replace('"', '\'').Replace("\r", @"\r").Replace("\n", @"\n") + "\",\"" +
                    submission.Sphere2Url.Replace('"', '\'').Replace("\r", @"\r").Replace("\n", @"\n") + "\"\n";
            }
            return new CsvFileData(_session.CourseOrg + "-" + _session.CourseId + "-" + _session.CourseRun + "-earth-spheres-images.csv",
                new System.Text.UTF8Encoding().GetBytes(data));
        }

        protected override string Create(HttpRequestBase request)
        {
            var res = "";

            try
            {
                var url1IsEmpty = String.IsNullOrWhiteSpace(request.Form["sphere1Url"].ToString());
                var url2IsEmpty = String.IsNullOrWhiteSpace(request.Form["sphere2Url"].ToString());
                var url1IsValidImageUrl = CanAccessImageUrl(request.Form["sphere1Url"].ToString());
                var url2IsValidImageUrl = CanAccessImageUrl(request.Form["sphere2Url"].ToString());
                double sphere1Latitude, sphere1Longitude, sphere2Latitude, sphere2Longitude;
                var sphere1LatitudeParsed = Double.TryParse(request.Form["sphere1Latitude"], out sphere1Latitude);
                var sphere1LongitudeParsed = Double.TryParse(request.Form["sphere1Longitude"], out sphere1Longitude);
                var sphere2LatitudeParsed = Double.TryParse(request.Form["sphere2Latitude"], out sphere2Latitude);
                var sphere2LongitudeParsed = Double.TryParse(request.Form["sphere2Longitude"], out sphere2Longitude);

                if ((!url1IsEmpty && (!sphere1LatitudeParsed || !sphere1LongitudeParsed)) ||
                    (!url2IsEmpty && (!sphere2LatitudeParsed || !sphere2LongitudeParsed)))
                {
                    res = "<span style='color: red;'>Failed to parse coordinates.</span>";
                }
                else
                {
                    var newSubmission = _sessionManager.DbContext.EarthSpheresImagesSubmissions.Add(new EarthSpheresImagesSubmission()
                    {
                        UserId = _session.UserId,
                        CourseOrg = _session.CourseOrg,
                        CourseId = _session.CourseId,
                        CourseRun = _session.CourseRun,
                        Sphere1Name = (url1IsValidImageUrl ? request.Form["sphere1Name"].ToString() : ""),
                        Sphere1Url = (url1IsValidImageUrl ? request.Form["sphere1Url"].ToString() : ""),
                        Sphere1Location = (url1IsValidImageUrl ? request.Form["sphere1Location"].ToString() : ""),
                        Sphere1Coordinate = (url1IsValidImageUrl ? new Coordinate(sphere1Latitude, sphere1Longitude) : null),
                        Sphere2Name = (url2IsValidImageUrl ? request.Form["sphere2Name"].ToString() : ""),
                        Sphere2Url = (url2IsValidImageUrl ? request.Form["sphere2Url"].ToString() : ""),
                        Sphere2Coordinate = (url2IsValidImageUrl ? new Coordinate(sphere2Latitude, sphere2Longitude) : null)
                    });

                    _sessionManager.DbContext.SaveChanges();

                    res = SubmitScore(newSubmission, url1IsEmpty, url1IsValidImageUrl, url2IsEmpty, url2IsValidImageUrl);
                }
            }
            catch (Exception e)
            {
                throw new Exception("Failed to create submission.", e);
            }

            return res;
        }

        protected override string Edit(HttpRequestBase request)
        {
            var res = "";

            try
            {
                var url1IsEmpty = String.IsNullOrWhiteSpace(request.Form["sphere1Url"].ToString());
                var url2IsEmpty = String.IsNullOrWhiteSpace(request.Form["sphere2Url"].ToString());
                var url1IsValidImageUrl = CanAccessImageUrl(request.Form["sphere1Url"].ToString());
                var url2IsValidImageUrl = CanAccessImageUrl(request.Form["sphere2Url"].ToString());
                double sphere1Latitude, sphere1Longitude, sphere2Latitude, sphere2Longitude;
                var sphere1LatitudeParsed = Double.TryParse(request.Form["sphere1Latitude"], out sphere1Latitude);
                var sphere1LongitudeParsed = Double.TryParse(request.Form["sphere1Longitude"], out sphere1Longitude);
                var sphere2LatitudeParsed = Double.TryParse(request.Form["sphere2Latitude"], out sphere2Latitude);
                var sphere2LongitudeParsed = Double.TryParse(request.Form["sphere2Longitude"], out sphere2Longitude);

                if ((!url1IsEmpty && (!sphere1LatitudeParsed || !sphere1LongitudeParsed)) ||
                    (!url2IsEmpty && (!sphere2LatitudeParsed || !sphere2LongitudeParsed)))
                {
                    res = "<span style='color: red;'>Failed to parse coordinates.</span>";
                }
                else
                {
                    EarthSpheresImagesSubmission existing =
                        (from o in _sessionManager.DbContext.EarthSpheresImagesSubmissions
                         where o.UserId == _session.UserId &&
                         o.CourseOrg == _session.CourseOrg &&
                         o.CourseId == _session.CourseId &&
                         o.CourseRun == _session.CourseRun
                         select o).SingleOrDefault();

                    existing.Sphere1Name = (url1IsValidImageUrl ? request.Form["sphere1Name"].ToString() : "");
                    existing.Sphere1Url = (url1IsValidImageUrl ? request.Form["sphere1Url"].ToString() : "");
                    existing.Sphere1Coordinate = (url1IsValidImageUrl ? new Coordinate(sphere1Latitude, sphere1Longitude) : null);
                    existing.Sphere2Name = (url2IsValidImageUrl ? request.Form["sphere2Name"].ToString() : "");
                    existing.Sphere2Url = (url2IsValidImageUrl ? request.Form["sphere2Url"].ToString() : "");
                    existing.Sphere2Coordinate = (url2IsValidImageUrl ? new Coordinate(sphere2Latitude, sphere2Longitude) : null);

                    _sessionManager.DbContext.SaveChanges();

                    res = SubmitScore(existing, url1IsEmpty, url1IsValidImageUrl, url2IsEmpty, url2IsValidImageUrl);
                }
            }
            catch (Exception e)
            {
                throw new Exception("Failed to edit existing student presentation.", e);
            }

            return res;
        }

        protected override ViewIdentifierAndModel GetViewIdentifierAndModel(string message)
        {
            return new ViewIdentifierAndModel("~/Views/EarthSpheresImageToolView.cshtml",
                new EarthSpheresImageToolViewModel()
                {
                    Submission = GetSubmissionForCurrentStudent(),
                    LtiSessionId = _session.Id.ToString(),
                    Roles = _session.LtiRequest.Roles,
                    ResponseMessage = message
                });
        }

        #region Private methods

        private EarthSpheresImagesSubmission GetSubmissionForCurrentStudent()
        {<commit_msg>Do not assign null to coordinate.<commit_after>﻿using ChalmersxTools.Models;
using ChalmersxTools.Models.Database;
using ChalmersxTools.Models.View;
using LtiLibrary.Core.Outcomes.v1;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web;

namespace ChalmersxTools.Tools
{
    public class EarthSpheresImageTool : SimpleDataStorageToolBase
    {
        public static readonly string CONSUMER_KEY = "ChalmersxEarthSpheresImageTool";

        public override string ConsumerKey { get { return CONSUMER_KEY; } }
        protected override string ConsumerSecret { get { return ConfigurationManager.AppSettings["ltiConsumerSecret"]; } }

        public override CsvFileData HandleDataRequest()
        {
            string data = "";
            data += "sphere1Name,sphere1Url,sphere2Name,sphere2Url\n";
            foreach (var submission in GetAllSubmissionsForCourseRun())
            {
                data += "\"" + submission.Sphere1Name.Replace('"', '\'').Replace("\r", @"\r").Replace("\n", @"\n") + "\",\"" +
                    submission.Sphere1Url.Replace('"', '\'').Replace("\r", @"\r").Replace("\n", @"\n") + "\",\"" +
                    submission.Sphere2Name.Replace('"', '\'').Replace("\r", @"\r").Replace("\n", @"\n") + "\",\"" +
                    submission.Sphere2Url.Replace('"', '\'').Replace("\r", @"\r").Replace("\n", @"\n") + "\"\n";
            }
            return new CsvFileData(_session.CourseOrg + "-" + _session.CourseId + "-" + _session.CourseRun + "-earth-spheres-images.csv",
                new System.Text.UTF8Encoding().GetBytes(data));
        }

        protected override string Create(HttpRequestBase request)
        {
            var res = "";

            try
            {
                var url1IsEmpty = String.IsNullOrWhiteSpace(request.Form["sphere1Url"].ToString());
                var url2IsEmpty = String.IsNullOrWhiteSpace(request.Form["sphere2Url"].ToString());
                var url1IsValidImageUrl = CanAccessImageUrl(request.Form["sphere1Url"].ToString());
                var url2IsValidImageUrl = CanAccessImageUrl(request.Form["sphere2Url"].ToString());
                double sphere1Latitude, sphere1Longitude, sphere2Latitude, sphere2Longitude;
                var sphere1LatitudeParsed = Double.TryParse(request.Form["sphere1Latitude"], out sphere1Latitude);
                var sphere1LongitudeParsed = Double.TryParse(request.Form["sphere1Longitude"], out sphere1Longitude);
                var sphere2LatitudeParsed = Double.TryParse(request.Form["sphere2Latitude"], out sphere2Latitude);
                var sphere2LongitudeParsed = Double.TryParse(request.Form["sphere2Longitude"], out sphere2Longitude);

                if ((!url1IsEmpty && (!sphere1LatitudeParsed || !sphere1LongitudeParsed)) ||
                    (!url2IsEmpty && (!sphere2LatitudeParsed || !sphere2LongitudeParsed)))
                {
                    res = "<span style='color: red;'>Failed to parse coordinates.</span>";
                }
                else
                {
                    var newSubmission = _sessionManager.DbContext.EarthSpheresImagesSubmissions.Add(new EarthSpheresImagesSubmission()
                    {
                        UserId = _session.UserId,
                        CourseOrg = _session.CourseOrg,
                        CourseId = _session.CourseId,
                        CourseRun = _session.CourseRun,
                        Sphere1Name = (url1IsValidImageUrl ? request.Form["sphere1Name"].ToString() : ""),
                        Sphere1Url = (url1IsValidImageUrl ? request.Form["sphere1Url"].ToString() : ""),
                        Sphere1Location = (url1IsValidImageUrl ? request.Form["sphere1Location"].ToString() : ""),
                        Sphere1Coordinate = (url1IsValidImageUrl ? new Coordinate(sphere1Latitude, sphere1Longitude) : new Coordinate()),
                        Sphere2Name = (url2IsValidImageUrl ? request.Form["sphere2Name"].ToString() : ""),
                        Sphere2Url = (url2IsValidImageUrl ? request.Form["sphere2Url"].ToString() : ""),
                        Sphere2Coordinate = (url2IsValidImageUrl ? new Coordinate(sphere2Latitude, sphere2Longitude) : new Coordinate())
                    });

                    _sessionManager.DbContext.SaveChanges();

                    res = SubmitScore(newSubmission, url1IsEmpty, url1IsValidImageUrl, url2IsEmpty, url2IsValidImageUrl);
                }
            }
            catch (Exception e)
            {
                throw new Exception("Failed to create submission.", e);
            }

            return res;
        }

        protected override string Edit(HttpRequestBase request)
        {
            var res = "";

            try
            {
                var url1IsEmpty = String.IsNullOrWhiteSpace(request.Form["sphere1Url"].ToString());
                var url2IsEmpty = String.IsNullOrWhiteSpace(request.Form["sphere2Url"].ToString());
                var url1IsValidImageUrl = CanAccessImageUrl(request.Form["sphere1Url"].ToString());
                var url2IsValidImageUrl = CanAccessImageUrl(request.Form["sphere2Url"].ToString());
                double sphere1Latitude, sphere1Longitude, sphere2Latitude, sphere2Longitude;
                var sphere1LatitudeParsed = Double.TryParse(request.Form["sphere1Latitude"], out sphere1Latitude);
                var sphere1LongitudeParsed = Double.TryParse(request.Form["sphere1Longitude"], out sphere1Longitude);
                var sphere2LatitudeParsed = Double.TryParse(request.Form["sphere2Latitude"], out sphere2Latitude);
                var sphere2LongitudeParsed = Double.TryParse(request.Form["sphere2Longitude"], out sphere2Longitude);

                if ((!url1IsEmpty && (!sphere1LatitudeParsed || !sphere1LongitudeParsed)) ||
                    (!url2IsEmpty && (!sphere2LatitudeParsed || !sphere2LongitudeParsed)))
                {
                    res = "<span style='color: red;'>Failed to parse coordinates.</span>";
                }
                else
                {
                    EarthSpheresImagesSubmission existing =
                        (from o in _sessionManager.DbContext.EarthSpheresImagesSubmissions
                         where o.UserId == _session.UserId &&
                         o.CourseOrg == _session.CourseOrg &&
                         o.CourseId == _session.CourseId &&
                         o.CourseRun == _session.CourseRun
                         select o).SingleOrDefault();

                    existing.Sphere1Name = (url1IsValidImageUrl ? request.Form["sphere1Name"].ToString() : "");
                    existing.Sphere1Url = (url1IsValidImageUrl ? request.Form["sphere1Url"].ToString() : "");
                    existing.Sphere1Coordinate = (url1IsValidImageUrl ? new Coordinate(sphere1Latitude, sphere1Longitude) : new Coordinate());
                    existing.Sphere2Name = (url2IsValidImageUrl ? request.Form["sphere2Name"].ToString() : "");
                    existing.Sphere2Url = (url2IsValidImageUrl ? request.Form["sphere2Url"].ToString() : "");
                    existing.Sphere2Coordinate = (url2IsValidImageUrl ? new Coordinate(sphere2Latitude, sphere2Longitude) : new Coordinate());

                    _sessionManager.DbContext.SaveChanges();

                    res = SubmitScore(existing, url1IsEmpty, url1IsValidImageUrl, url2IsEmpty, url2IsValidImageUrl);
                }
            }
            catch (Exception e)
            {
                throw new Exception("Failed to edit existing student presentation.", e);
            }

            return res;
        }

        protected override ViewIdentifierAndModel GetViewIdentifierAndModel(string message)
        {
            return new ViewIdentifierAndModel("~/Views/EarthSpheresImageToolView.cshtml",
                new EarthSpheresImageToolViewModel()
                {
                    Submission = GetSubmissionForCurrentStudent(),
                    LtiSessionId = _session.Id.ToString(),
                    Roles = _session.LtiRequest.Roles,
                    ResponseMessage = message
                });
        }

        #region Private methods

        private EarthSpheresImagesSubmission GetSubmissionForCurrentStudent()
        {
{'fraction_non_alphanumeric': 0.11034358481499279, 'fraction_numerical': 0.014536280634310427, 'mean_word_length': 2.1538170107974994, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3216310', 'n_tokens_mistral': 4464, 'n_tokens_neox': 4123, 'n_words': 707}