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

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

namespace MagicSquareExample
{
    public interface MagicSquare
    {
        double[,] mymagic(int i);
    }

    public class Magic
    {
        static void Main(string[] args)
        {
            MWClient client = new MWHttpClient();

            try
            {                
                MagicSquare mSq = client.CreateProxy<MagicSquare>( new Uri(args[0]) );
                double[,] magic = mSq.mymagic( Convert.ToInt32(args[1]) );
                PrintMagic(magic);                
            }
            catch (MATLABException ex)
            {
                Console.WriteLine("MATLAB error thrown : ");
                Console.WriteLine(ex.MATLABIdentifier);
                Console.WriteLine(ex.MATLABStackTraceString);
            }
            catch (WebException ex)
            {
                HttpWebResponse response = (HttpWebResponse)ex.Response;
                if (response != null)
                {
                    Console.WriteLine("Status code : " + response.StatusCode);
                    Console.WriteLine("Status description : " + response.StatusDescription);
                }
                else
                {
                    Console.WriteLine("No response received in WebException with status : " + ex.Status);
                }
            }            
            finally
            {
                if (client != null)
                {
                    client.Dispose();
                }
            }
        }

        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();
            }
        }
    }
}
