using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CARRE_DSS2.Models;
using RestSharp;

namespace CARRE_DSS2.Models
{
    public class CarreRestFull
    {
        private class PatientRest
        {
            public string username { get; set; }
            public string graphName { get; set; }
            public string email { get; set; }
        }

        public class MeasurmentListItemRest
        {
            public DateTime lastMeasured { get; set; }
            public DateTime firstMeasured { get; set; }
            public string measurement { get; set; }
        }

        public Patient validateToken(string token)
        {

            var request = new RestRequest();
            request.Resource = "userProfile";

            var response = processRequest<PatientRest>(token, request);

            if (response.ErrorException != null || response.Data.email == null)
            {
                return null;
            }

            var retP = new Patient()
            {
                UserName = response.Data.username,
                GraphName = response.Data.graphName,
                Email = response.Data.email,
                Token = token
            };

            return retP;

        }

        public List<MeasurmentListItemRest> getMeasurmentsList(string token)
        {
            var request = new RestRequest();
            request.Resource = "measurementsList";

            var response = processRequest<List<MeasurmentListItemRest>>(token, request);

            if (response.ErrorException != null || !response.Data.Any())
            {
                return null;
            }

            return response.Data;
        }

        private IRestResponse<T> processRequest<T>(string token, RestRequest request) where T : new()
        {
            var client = new RestClient();
            client.BaseUrl = new Uri("http://carre.kmi.open.ac.uk:80/ws/");

            request.AddQueryParameter("token", token);
            var response = client.Execute<T>(request);
            return response;
        }


    }
}