using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RestSharp;

namespace ETC_App1
{
    public class HyperLPR
    {
        public Server server { get; set; } = new Server();

        public HyperLPR()
        {
            if (!File.Exists("server.json"))
            {
                //server.Host = "192.168.6.58";
                server.Host = "192.168.6.59";

                //server.Port = 80;
                server.Port = 80;

                server.Resource = "recognition";

                Save();
            }
            else {
                StreamReader f = new StreamReader("server.json");
                server = JsonConvert.DeserializeObject<Server>(f.ReadToEnd());
                f.Close();
            }
        }

        public Json Process(string filename)
        {
            RestClient client = new RestClient("http://" + server.Host + ":" + server.Port);

            RestRequest request = new RestRequest(server.Resource, Method.POST);

            //request.Timeout = 60;

            request.AddFile("file", filename);

            RestResponse response = client.Execute(request) as RestResponse;

            try
            {
                Json json = JsonConvert.DeserializeObject<Json>(response.Content);

                json.filename = filename;

                return json;
            }
            catch (Exception ex)
            {
                return new Json() { filename = filename, message2 = ex.Message };
            }
        }

        public void Save()
        {
            StreamWriter stream = new StreamWriter("server.json");

            stream.Write(JsonConvert.SerializeObject(server,Formatting.Indented));

            stream.Flush();

            stream.Close();
        }
    }
}
