﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using IndianHealthService.BMXNet;
using System.Reflection;
using IndianHealthService.BMXNet.Model;
 
using IndianHealthService.BMXNet.WinForm;

namespace IndianHealthService.BMXNet.TestBench
{
    public partial class ComponentTester : Form
    {
        public ComponentTester()
        {
            InitializeComponent();
        }

     
        protected void Login()
        {
                
            this.LoginToRpms();
            this.PostLoginToRpms();
        }

        private BMXNetConnectInfo _bmxBroker=null;

public BMXNetConnectInfo BmxBroker
{
  get { return _bmxBroker; }
  set { _bmxBroker = value; }
}

private String _rpmsConnectionInfo = "";

public String RpmsConnectionInfo
{
    get { return _rpmsConnectionInfo; }
    set { _rpmsConnectionInfo = value; }
}

private DesktopFramework _broker = new DesktopFramework();

public DesktopFramework Framework
{
    get { return _broker; }
    set { _broker = value; }
}

protected virtual void LoginToRpms()
{
    this.BmxBroker = new BMXNetConnectInfo();
    String[] peices = this.RpmsConnectionInfo.Split(new char[] { '~' });
    this.BmxBroker.LoadConnectInfo(peices[0],int.Parse(peices[1]),peices[2],peices[3]);
    if (this.BmxBroker.Connected)
    {
        this.Framework= DesktopFramework.OpenOn(this.BmxBroker.Broker.OpenRpcSession());
        this.NonComponentSession = this.Framework.OpenSession();
        this.NonComponentSession.Logger = this.transcript;
        this.NonComponentSession.Log("Bench", "Access", "Logged in");
   
    }
    else
    {

        MessageBox.Show("Unable to log in to RPMS");
    }
}


        private Context _context;

        public Context Context
        {
            get { return _context; }
            set { _context = value; }
        }

        private DesktopSession _nonComponentSession = null;

        public DesktopSession NonComponentSession
        {
            get { return _nonComponentSession; }
            set { _nonComponentSession = value; }
        }

                 
        protected void PostLoginToRpms()
        {
            if (this.NonComponentSession != null)
            {
                this.Context = this.NonComponentSession.Context;
                this.Context.Changed += new EventHandler<ContextChangedArgs>(Context_Changed);

            }
            else
            {
                this.Context = null;
            }
        }

        void Context_Changed(object sender, ContextChangedArgs e)
        {
            this.UpdateTitle();
        }

        private void UpdateTitle()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(this.HostedControl == null ? "[No Component]" : this.ComponentClassName);
            this.Text = builder.ToString();
      
            builder = new StringBuilder();
            builder.Append(this.Context.HasPatient ? this.Context.Patient.PatientName : "[No Patient]");
            builder.Append(" :: ");
            builder.Append(this.Context.HasVisit ? this.Context.Visit.Ien : "[No Visit]");
            this.contextLabel.Text = builder.ToString();       
        }
   
               
        private void ComponentTester_Load(object sender, EventArgs e)
        {        
            this.ParseCommandLine();

            this.Login();

            if (this.Context == null)
            {
                MessageBox.Show("Unable to create context");
                this.Close();
            }
            else
            {
                this.InitializeContext(); 
                this.CreateHostedControl();
                this.UpdateTitle();
            }

        
 
        }

        private void InitializeContext()
        {
            if (this.InitialChart != null)
            {
                Patient hit = this.NonComponentSession.FindPatientFromChart(this.InitialChart, false);
                if (hit != null)
                {
                    this.Framework.ChangePatient(hit);
                }
            }
        }

        private String _componentClassName;

        public String ComponentClassName
        {
          get { return _componentClassName; }
          set { _componentClassName = value; }
        }
                private String _componentAssemblyName;

        public String ComponentAssemblyName
        {
          get { return _componentAssemblyName; }
          set { _componentAssemblyName = value; }
        }
                private String _initialChart;

        public String InitialChart
        {
          get { return _initialChart; }
          set { _initialChart = value; }
        }
                private String _initialIen;

        public String InitialIen
        {
          get { return _initialIen; }
          set { _initialIen = value; }
        }
                private String _initialVisitDate;

        public String InitialVisitDate
        {
          get { return _initialVisitDate; }
          set { _initialVisitDate = value; }
        }

        private void ParseCommandLine()
        {

            String[] args = Environment.GetCommandLineArgs();

            foreach (String set in args)
            {
                String[] split = set.Split(new char[] { ':' });
                if (split[0].Equals(@"/class"))
                {
                    this.ComponentClassName = split[1];
                }
                else if (split[0].Equals(@"/assembly"))
                {
                    this.ComponentAssemblyName = split[1];
                }
                else if (split[0].Equals(@"/chart"))
                {
                    this.InitialChart = split[1];
                }
                else if (split[0].Equals(@"/ien"))
                {
                    this.InitialIen = split[1];
                }
                else if (split[0].Equals(@"/rpms"))
                {
                    this.RpmsConnectionInfo = split[1];
                }
                else if (split[0].Equals(@"/visit"))
                {
                    this.InitialVisitDate = split[1];
                } if (split[0].Equals(@"/property"))
                {
                    String parameters= split[1];
                    String[] pair=parameters.Split(new char[] {'~'});
                    this.PropertyPairs.Add(pair[0],pair[1].Replace("_"," "));
                }
            }
        }

        private SortedDictionary<String, String> _propertyPairs = new SortedDictionary<string, string>();

        public SortedDictionary<String, String> PropertyPairs
        {
            get { return _propertyPairs; }
            set { _propertyPairs = value; }
        }

        private void CreateHostedControl()
        {
            try
            {     
                Assembly componentAssembly = Assembly.LoadFrom(this.ComponentAssemblyName);
        
                this.HostedControl = (UserControl)componentAssembly.CreateInstance(this.ComponentClassName);
                DesktopSession session = this.Framework.OpenSession();
                session.Logger = this.transcript;

                (this.HostedControl as ModelConsumer).Session = session;
                (this.HostedControl as BMXNetConsumer).Bmx= this.Framework.Bmx;

                foreach (String key in this.PropertyPairs.Keys)
                {
                    PropertyInfo property = this.HostedControl.GetType().GetProperty(key);
                    property.SetValue(this.HostedControl, this.PropertyPairs[key],null);
                }

                this.ClientSize = this.HostedControl.Size;
                this.HostedControl.Dock = DockStyle.Fill;
                this.componentHolder.Controls.Add(this.HostedControl);

            }
            catch 
            {
                MessageBox.Show("Unable to create control from command line " + Environment.CommandLine);
            }
        }
            

        private UserControl _hostedControl = null;

        public UserControl HostedControl
        {
            get { return _hostedControl; }
            set { _hostedControl = value; }
        }

        private void loginToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Login();
        }

        private void changePatientToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.contextLabel_Click(null, null);
        }

     

        private void resetToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Framework.ChangePatient(null);
        }

        private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
        {

        }



        private void contextLabel_Click(object sender, EventArgs e)
        {
            PatientVisitPicker dialog = new PatientVisitPicker();
            dialog.DesktopSession = this.NonComponentSession;
            dialog.Framework = this.Framework;
            dialog.Context = this.Context;

            if (dialog.ShowDialog() == DialogResult.OK)
            {
            }


        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutDialog dialog = new AboutDialog();
            dialog.ShowDialog();
        }

    }
}