using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using FastReport.Utils;
using FastReport.Data;
using FastReport.Data.ConnectionEditors;

namespace FastReport.Forms
{
    internal partial class ConnectionForm : BaseDialogForm
    {
        private DataConnectionBase connection;
        private ConnectionEditorBase connectionEditor;
        private bool editMode;

        public DataConnectionBase Connection
        {
            get { return connection; }
            set { connection = value; }
        }

        public bool EditMode
        {
            get { return editMode; }
            set
            {
                editMode = value;
                if (value)
                {
                    cbxConnections.Items.Clear();
                    cbxConnections.Items.Add(RegisteredObjects.FindConnection(Connection.GetType()));
                    cbxConnections.SelectedIndex = 0;
                    cbxConnections.Enabled = false;
                    cbAlwaysUse.Enabled = false;
                }
            }
        }

        private void EnumConnections()
        {
            var registeredObjects = new List<DataConnectionInfo>();
            RegisteredObjects.DataConnections.EnumItems(registeredObjects);
            string lastUsed = Config.Root.FindItem("Forms").FindItem(Name).GetProp("ConnectionType");

            foreach (var info in registeredObjects)
            {
                if (info.Object != null)
                {
                    cbxConnections.Items.Add(info);
                    if (info.Object.Name == lastUsed)
                    {
                        cbxConnections.SelectedIndex = cbxConnections.Items.Count - 1;
                        cbAlwaysUse.Checked = true;
                    }
                }
            }

            if (cbxConnections.SelectedIndex == -1)
                cbxConnections.SelectedIndex = 0;
        }

        private bool TestConnection(bool showOkMessage)
        {
            string saveConnectionString = connection.ConnectionString;
            connection.ConnectionString = connectionEditor.ConnectionString;
            bool successful = true;
            string errorMsg = "";
            try
            {
                connection.TestConnection();
            }
            catch (Exception e)
            {
                successful = false;
                errorMsg = e.Message;
            }
            connection.ConnectionString = saveConnectionString;

            if (successful && showOkMessage)
                FRMessageBox.Information(Res.Get("Forms,Connection,TestSuccesful"));
            else if (!successful)
                FRMessageBox.Error(errorMsg);
            return successful;
        }

        private void cbxConnections_DrawItem(object sender, DrawItemEventArgs e)
        {
            e.DrawBackground();
            if (e.Index >= 0)
            {
                var info = cbxConnections.Items[e.Index] as DataConnectionInfo;
                TextFormatFlags flags = RightToLeft == RightToLeft.Yes ? TextFormatFlags.RightToLeft | TextFormatFlags.Right : TextFormatFlags.Default;
                TextRenderer.DrawText(e.Graphics, Res.TryGet(info.Text), e.Font, e.Bounds, e.ForeColor, flags);
            }
        }

        private void ConnectionForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (cbAlwaysUse.Checked)
            {
                Config.Root.FindItem("Forms").FindItem(Name).SetProp("ConnectionType",
                  (cbxConnections.SelectedItem as DataConnectionInfo).Object.Name);
            }
        }

        private void ConnectionForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult == DialogResult.OK && connection != null && connectionEditor != null)
            {
                connection.LoginPrompt = cbLoginPrompt.Checked;
                if (connection.LoginPrompt || TestConnection(false))
                    connection.ConnectionString = connectionEditor.ConnectionString;
                else
                    e.Cancel = true;
            }
        }

        private void cbxConnections_SelectedIndexChanged(object sender, EventArgs e)
        {
            cbAlwaysUse.Checked = false;
            SuspendLayout();
            if (connectionEditor != null)
                connectionEditor.Dispose();
            if (!editMode)
            {
                if (connection != null)
                    connection.Dispose();
                connection = null;

                Type connectionType = (cbxConnections.SelectedItem as DataConnectionInfo).Object;
                connection = Activator.CreateInstance(connectionType) as DataConnectionBase;
            }
            connectionEditor = connection.GetEditor();

            connectionEditor.TabIndex = 3;

            if (connectionEditor != null)
            {
                connectionEditor.Parent = this;
                connectionEditor.Scale(new SizeF(this.DpiMultiplier(), this.DpiMultiplier()));
                UIUtils.CheckRTL(connectionEditor);
                connectionEditor.UpdateDpiDependencies();
                connectionEditor.Location = new Point(0, gbSelect.Bottom);
                ClientSize = new Size(ClientSize.Width,
                  connectionEditor.Bottom + cbLoginPrompt.Height + btnOk.Height + gbSelect.Top * 5);
            }
            else
                ClientSize = new Size(ClientSize.Width,
                gbSelect.Bottom + cbLoginPrompt.Height + btnOk.Height + gbSelect.Top * 5);

            ResumeLayout();
            Refresh();
            if (connection != null && connectionEditor != null)
            {
                connectionEditor.ConnectionString = connection.ConnectionString;
                cbLoginPrompt.Checked = connection.LoginPrompt;
            }
            btnTest.Enabled = connection != null;
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            TestConnection(true);
        }

        public override void Localize()
        {
            base.Localize();
            MyRes res = new MyRes("Forms,Connection");
            Text = res.Get("");
            gbSelect.Text = res.Get("Select");
            cbAlwaysUse.Text = res.Get("AlwaysUse");
            cbLoginPrompt.Text = res.Get("LoginPrompt");
            btnTest.Text = res.Get("Test");
        }

        public override void UpdateDpiDependencies()
        {
            base.UpdateDpiDependencies();
            if (connectionEditor != null)
                connectionEditor.UpdateDpiDependencies();
        }

        public ConnectionForm()
        {
            InitializeComponent();
            Localize();
            UIUtils.CheckRTL(this);
            UpdateDpiDependencies();
            EnumConnections();
        }
    }
}

