import com.mathworks.mps.client.MATLABException;
import com.mathworks.mps.client.MWDefaultMarshalingRules;
import com.mathworks.mps.client.rest.MATLABParams;
import com.mathworks.mps.client.rest.MATLABResult;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


class StudentMarshaller extends MWDefaultMarshalingRules {
    @Override
    public List<Class> getStructTypes() {
        List structType = new ArrayList();
        structType.add(Student.class);
        return structType;
    }
}


public class SortStudentsSyncREST {
	final static protected String CONTENT_TYPE = "application/x-google-protobuf";

    public static void main(String[] args) {

        // Create a Student array.
        Student[] students = new Student[]{new Student("Toni Miller", 90, "A"),
                new Student("Ed Plum", 80, "B+"),
                new Student("Mark Jones", 85, "A-")};

        // Use the java.net package's URLConnection as HTTP Client in this example.
        try {
            String mpsBaseUrl = "http://localhost:9910";
            URL url;
            url = new URL(mpsBaseUrl + "/sortstudents/sortstudents");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            //Set Content-Type to protobuf.
            urlConnection.setRequestProperty("Content-Type", CONTENT_TYPE);


            // Make the initial POST request body with MATLABParams class.
            MATLABParams mlMakeBody = MATLABParams.newInstance(1, Student[].class, new StudentMarshaller(), new Object[]{students});

            // Write the MATLABParams object into the output stream of the HTTP request.
            OutputStream output = urlConnection.getOutputStream();
            output.write(mlMakeBody.getRequestBody());
            output.flush();

            // Parse the response body of the above HTTP request using methods from MATLABResult class. 
			// The MATLABParams object created earlier is an input argument to the newInstance method.
            // If there is any error in MATLAB, call to getResult() throws a MATLABException which contains the error message
            // displayed in MATLAB.
            MATLABResult mlFinalResult = MATLABResult.newInstance(mlMakeBody, urlConnection.getInputStream());
            Student[] magicSq = (Student[]) mlFinalResult.getResult();
            for (Student student :
                    magicSq) {
                System.out.println(student);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } 

    }
}
