using System;
using System.IO;
using System.Net;
using System.Net.Http;
using models;
using UnityEngine;

namespace utils
{
    public class Api<T>
    {
        public static String API_URL = "https://iot.epi.cb85.software";
        public static int API_TIMEOUT = 10000;
        
        public static HttpWebRequest createClient(String suffix) {
            return (HttpWebRequest)WebRequest.Create(API_URL + suffix);
        }

        public static T get(String suffix, String token)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(API_URL + suffix);
            request.Accept = "application/json";
            request.Method = "GET";
            request.Headers.Add("Authorization", token);
            request.Timeout=API_TIMEOUT;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response == null)
            {
                throw new Exception("Response is null");
            }
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string jsonResponse = reader.ReadToEnd();
            T responseData = JsonUtility.FromJson<T>(jsonResponse);
            response.Close();
            return responseData;
        }

        public static T post(String suffix, String body)
        {
            HttpWebRequest request = createClient(suffix);
            request.ContentType = "application/json";
            request.Method = "POST";
            request.Timeout=API_TIMEOUT;
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(body);
                streamWriter.Flush();
                streamWriter.Close();
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string jsonResponse = reader.ReadToEnd();
            T responseData = JsonUtility.FromJson<T>(jsonResponse);
            response.Close();
            return responseData;
        }
    }
}