using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using CARRE_DSS2.Models;

namespace CARRE_DSS2.Models
{
    public class Measurement
    {
        [NotMapped]
        private ApplicationDbContext db = null;
        [NotMapped]
        private Observable savedObsv = null;
        [NotMapped]
        private MeasurementBinding savedBind = null;


        private void init()
        {
            if(db == null)
            {
                db = new ApplicationDbContext();
                if (db.MeasurementBindings.Where(b => b.MeasurementNode == Node).Any())
                {
                    savedBind = db.MeasurementBindings.Where(b => b.MeasurementNode == Node).First();
                    if(savedBind.ObservableNode != null && savedBind.ObservableNode != "")
                    {
                        savedObsv = db.Observables.Where(o => o.Node == savedBind.ObservableNode).First();
                    }
                }
            }
        }

        public Observable bindedObservable
        {
            get
            {
                init();
                return savedObsv;
            }
        }

        public Measurement(Patient sourcePatient, string node, DateTime lastMeasured = new DateTime(), DateTime firstMeasured = new DateTime())
        {
            this.SourcePatient = sourcePatient;
            this.Node = node;
            this.LastMeasured = lastMeasured;
            this.FirstMeasured = firstMeasured;
        }

        public Patient SourcePatient { get; }

        public string lastMeasurmentValue()
        {
            throw new NotImplementedException();
        }

        public Tuple<List<DateTime>,List<String>> measurmentsFromTo(DateTime from, DateTime to)
        {
            throw new NotImplementedException();
        }

        public Tuple<List<DateTime>, List<String>> measumentsFromLastPeriod(TimeSpan period)
        {
            return measurmentsFromTo(DateTime.Now - period, DateTime.Now);
        }

        [Key]
        [Display(Name = "Node")]
        public string Node { get; set; }

        [Display(Name = "Name")]
        public string Name
        {
            get {
                init();
                if (savedBind == null)
                    return Node;
                else
                    return savedBind.Name;
            }
        }

        [Display(Name = "Last measured")]
        public DateTime LastMeasured { get; set; }

        [Display(Name = "First measured")]
        public DateTime FirstMeasured { get; set; }

    }
}