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

namespace IndianHealthService.BMXNet.CIA
{
    internal class CiaPatientContext : CiaObject, PatientContext
    {

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

            answer.Session = aSession;
            answer.HookEvents(eventSource);
        
            return answer;
        }

        private CiaSession _session=null;

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


        #region PatientContext Members

        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)
        {
            if (e.IsPatientChange)
            {
                this.Patient = CiaPatient.FindCurrent(this.Session);
            }

            if (e.IsVisitChange)
            {
                this.Encounter= CiaEncounter.FindCurrent(this.Session);
            }


            if (this.Changed != null)
                this.Changed.Invoke(sender, e); ;
        }

        Patient _patient = null;

        public Patient Patient
        {
            get { return _patient; }
            set { _patient = value; }
        }

        private Encounter _encounter = null;

        public Encounter Encounter
        {
            get { return _encounter; }
            set { _encounter = value; }
        }


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

        public bool HasEncounter
        {
            get { return this.Encounter != null; }
        }

        #endregion
    }
}