// Copyright 1984-2020 The MathWorks, Inc.
// All Rights Reserved.

using System;
using System.Net;
using MathWorks.MATLAB.ProductionServer.Client;
using MathWorks.MATLAB.ProductionServer.Client.REST;
using System.Collections.Generic;

namespace MagicSquareExample
{
    public class MagicSync
    {
        static void Main(string[] args)
        {
            //Sync request using RESTful API and protobuf.

            // URL of the MATLAB Production Server.			
            String mpsBaseUrl = "http://localhost:9910";

            Console.WriteLine("Sending the POST request to the URL: "+ mpsBaseUrl + "/mymagic/mymagic.");
            var firstRequest = (HttpWebRequest)WebRequest.Create(mpsBaseUrl + "/mymagic/mymagic");
            firstRequest.Method = "POST";

            //Set Content-Type HTTP header to protobuf.
            firstRequest.ContentType = "application/x-google-protobuf";

            //Use MATLABParams class to make POST request body.
            MATLABParams mlParams = MATLABParams.Create(1, new List<Type> { typeof(double[,]) }, 2);
            mlParams.WriteTo(firstRequest.GetRequestStream());
            var response = (HttpWebResponse)firstRequest.GetResponse();
            Console.WriteLine("The HTTP status code of the request is "+response.StatusCode+". \n\n");

            //If there is a MATLAB error, call to Result<>() throws MATLABException which contains the error message displayed in MATLAB.
            Console.WriteLine("Parsing the result from the response of the HTTP Request using the MATLABResult class.\n\n");
            MATLABResult mlResult;
            mlResult = MATLABResult.Create(mlParams, response.GetResponseStream());
            try
            {
                double[,] result = mlResult.Result<double[,]>();
                Console.WriteLine("Printing the 2-D array...\n");
                PrintMagic(result);
            }
            catch (MATLABException e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.ReadKey();
        }

        static void PrintMagic(double[,] magic)
        {
            int numDims = magic.Rank;
            int[] dims = new int[numDims];

            for (int i = 0; i < numDims; i++)
            {
                dims[i] = magic.GetLength(i);
            }

            for (int j = 0; j < dims[0]; j++)
            {
                for (int k = 0; k < dims[1]; k++)
                {
                    Console.Write(magic[j, k]);
                    if (k < dims[1] - 1)
                    {
                        Console.Write(",");
                    }
                }
                Console.WriteLine();
            }
        }
    }
}