package studentcapture.feedback;

import java.net.URI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import javax.validation.Valid;
import java.util.HashMap;
import studentcapture.assignment.AssignmentModel;
import studentcapture.lti.*;

/**
 * Will deliver or update information about feedback on a Submission for an
 * Assignment.
 *
 * @author Group4, Group6
 * @see AssignmentModel
 * @see FeedbackModel
 * @version 0.3 05/02/16 Ongoing - Fixed db-request on set.
 * @since 0.2, 04/29/16 Fixed model.
 * @since 0.1, 04/28/16 Added "set"-mapping method.
 */

@RestController
@RequestMapping(value = "feedback")
public class FeedbackController {
    private static final String dbURI = "https://localhost:8443";


    @Autowired
    private RestTemplate requestSender;

    @CrossOrigin
    @RequestMapping(value = "get", method = RequestMethod.GET)
    public HashMap handleFeedbackRequestFromStudent(@Valid FeedbackModel model) {
        //TODO Unsafe data needs to be cleaned
        URI targetUrl = UriComponentsBuilder.fromUriString(dbURI)
                .path("DB/getGrade")
                .queryParam("studentID", model.getStudentID())
                .queryParam("assignmentID", model.getAssignmentID())
                .queryParam("courseID", model.getCourseID())
                .build()
                .toUri();

        HashMap<String, String> response;
        try {
            response = requestSender.getForObject(targetUrl, HashMap.class);
        } catch (RestClientException e) {
            //TODO Maybe not good to send exceptions to browser?
            response = new HashMap<String, String>();
            response.put("error", e.getMessage());
        }
        return response;
    }

    /**
     * Will set the given grade for the Feedback.
     * @param fm The given feedback that will be inserted/updated.
     * @see LTICommunicator
     * @see FeedbackModel
     */
    @RequestMapping(value = "set", method = RequestMethod.POST)
    public HashMap<String, String> setFeedback(@RequestBody FeedbackModel fm) {

        URI targetUrl = UriComponentsBuilder.fromUriString(dbURI)
                .path("DB/setGrade")
                .queryParam("assID", String.valueOf(fm.getAssignmentID()))
                .queryParam("teacherID", fm.getTeacherID())
                .queryParam("studentID", String.valueOf(fm.getStudentID()))
                .queryParam("grade", fm.getGrade())
                .build()
                .toUri();
        HashMap<String, String> addToDB = getExternalResponse(targetUrl);
        if (addToDB.containsKey("error")) {
            return addToDB;
        }


        //TODO: Set grade in LTI.
        try {
            LTICommunicator.setGrade(fm);
        }
        catch (LTIInvalidGradeException e) {
            //TODO: Will need to notify the client.
            e.printStackTrace();
        } catch (LTINullPointerException e) {
            //TODO: Ignore.
            e.printStackTrace();
        } catch (LTISignatureException e) {
            //TODO: Will need to notify system administrator.
            e.printStackTrace();
        }

        return addToDB;

    }


    /**
     * Will call an external HTTP, will save response in HashMap.
     * @param targetUrl The URI that will be called.
     * @return  HashMap of the response.
     */
    public HashMap<String, String> getExternalResponse(URI targetUrl) {
        HashMap<String, String> response;
        try {
            response = requestSender.getForObject(targetUrl, HashMap.class);
        } catch (RestClientException e) {
            //TODO Maybe not good to send exceptions to browser?
            response = new HashMap<String, String>();
            response.put("error", e.getMessage());
        }
        return response;
    }





}

@@ -111,16 +111,124 @@
 owired;%0A
+import org.springframework.http.*;%0Aimport org.springframework.http.converter.ByteArrayHttpMessageConverter;%0A
 import o
@@ -469,16 +469,41 @@
 .Valid;%0A
+import java.util.Arrays;%0A
 import j
@@ -2074,24 +2074,1030 @@
 nse;%0A    %7D%0A%0A
+    @CrossOrigin%0A    @RequestMapping(value = %22video%22, method = RequestMethod.GET)%0A    public ResponseEntity%3Cbyte%5B%5D%3E video(@Valid FeedbackModel model) %7B%0A%0A        HttpHeaders headers = new HttpHeaders();%0A        headers.setAccept(Arrays.asList(MediaType.ALL));%0A        HttpEntity%3CString%3E entity = new HttpEntity(headers);%0A        ResponseEntity%3Cbyte%5B%5D%3E response = null;%0A%0A        URI targetUrl = UriComponentsBuilder.fromUriString(dbURI + %22/videoDownload/%22)%0A                .path(Integer.toString(model.getCourseCode()) + %22/%22 +%0A                      Integer.toString(model.getCourseID()) + %22/%22 +%0A                      Integer.toString(model.getAssignmentID()) + %22/%22 +%0A                      Integer.toString(model.getStudentID()))%0A                .build()%0A                .toUri();%0A        try %7B%0A            response = requestSender.exchange(targetUrl, HttpMethod.GET, entity, byte%5B%5D.class);%0A        %7D catch (RestClientException e) %7B%0A            //TODO Error handling%0A        %7D%0A        return response;%0A    %7D%0A%0A
     /**%0A    

Add function for getting feedback video.