using System;
using System.Collections.Generic;
using System.Text;
using IndianHealthService.BMXNet.Model;

namespace IndianHealthService.BMXNet.EHR.Model
{
    internal class CiaContext : CiaObject, Context
    {

        internal static CiaContext CreateFrom(CiaSession aSession, IEhrEvents eventSource)
        {
            CiaContext answer = new CiaContext();

            answer.Initialize(aSession);
            answer.HookEvents(eventSource);

            return answer;
        }

        private void Initialize(CiaSession aSession)
        {
            this.Session = aSession;
            this.Patient = CiaPatient.FindCurrent(this.Session);
        }

        private CiaSession _session=null;

        internal CiaSession Session
        {
            get { return _session; }
            set { _session = value; }
        }


        public event EventHandler<ContextChangedArgs> Changed;

        public event EventHandler<ContextChangingArgs> Changing;

        internal void HookEvents(IEhrEvents eventSource)
        {
            eventSource.ContextChanged += new EventHandler<ContextChangedArgs>(aComponent_ContextChanged);
            eventSource.ContextChanging += new EventHandler<ContextChangingArgs>(aComponent_ContextChanging);
        }

        private void aComponent_ContextChanging(object sender, ContextChangingArgs e)
        {
            if (this.Changing != null)
                this.Changing.Invoke(sender, e);
        }

        void aComponent_ContextChanged(object sender, ContextChangedArgs e)
        {
            this.Patient = CiaPatient.FindCurrent(this.Session);
      
            if (this.Changed != null)
                this.Changed.Invoke(sender, e); ;
        }

        public Visit Visit
        {
            get { return CiaVisit.FindCurrent(this.Session); }
        }

        public bool HasUnlockedVisit
        {
            get {
                Visit visit = this.Visit;
                return visit != null && (!visit.IsLocked) && (!visit.IsStub);
            }
        }

        Patient _patient = null;

        public Patient Patient
        {
            get { return _patient; }
            set { _patient = value; }
        }
 
        public bool HasPatient
        {
            get { return this.Patient != null; }
        }

        public bool HasVisit
        {
            get { return this.Visit != null; }
        }

        public User User
        {
            get { return this.Session.User; }
        }

    }
}