using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Configuration;
using Baza_Reklam.Classes.Model;

namespace Baza_Reklam
{
    public partial class Logowanie : Form
    {

        #region Fields (2)

        private bool loginResult;
        private readonly SqlConnectionStringBuilder sqlBldr = new SqlConnectionStringBuilder();

        #endregion Fields

        #region Constructors (1)

        public Logowanie()
        {
            InitializeComponent();

            label4.Text = "Wersja " + Application.ProductVersion;
            //+ Baza_Reklam.Classes.Version.nrWersji;

            foreach (ConnectionStringSettings s2 in ConfigurationManager.ConnectionStrings)
            {
                bazyComboBox.Items.Add(s2.Name);
            }

            bazyComboBox.SelectedIndex = 0;

        }

        #endregion Constructors

        #region Methods (6)


        // Private Methods (6) 

        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text.Trim()) || string.IsNullOrEmpty(textBox2.Text.Trim())) return;

            komunikatLabel.Text = "";

            Cursor = Cursors.WaitCursor;
            loginResult = LoginTest();
            Cursor = Cursors.Default;

            if (loginResult)
            {
                Cursor = Cursors.WaitCursor;

                if (SprawdzWersje())
                {
                    if (Login())
                    {
                        DialogResult = DialogResult.OK;
                    }
                    else
                    {
                        komunikatLabel.Text = "Konto nieaktywne lub brak uprawnień.";
                    }
                }
                else
                {
                    Close();
                    return;
                }
                Cursor = Cursors.Default;
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            linkLabel1.LinkVisited = true;

            System.Diagnostics.ProcessStartInfo n = new System.Diagnostics.ProcessStartInfo();
            n.CreateNoWindow = true;
            n.FileName = "www.infocity.pl/baza_reklam/instrukcja.htm";
            System.Diagnostics.Process.Start(n);

        }

        private bool Login()
        {
            ConnString.getConnString().Value = sqlBldr.ConnectionString;

            SqlConnection conn = new SqlConnection(sqlBldr.ConnectionString);

            //zczytyje prawa uzytkownika
            SqlCommand command = new SqlCommand();

            command.CommandType = CommandType.Text;
            command.CommandText = "SELECT U.*, UA.AgencyId, UA.Name, UA.[Order] FROM dbo.UZYTKOWNICY U LEFT OUTER JOIN dbo.UserAgency UA ON UA.UserId=U.Id WHERE U.LOGIN=@login ORDER BY UA.[Order]";
            command.Parameters.AddWithValue("@login", textBox1.Text);
            command.Connection = conn;

            conn.Open();

            SqlDataReader reader = command.ExecuteReader();

            User.Instance().Login = textBox1.Text;
            User.Instance().Password = textBox2.Text;

            if (reader.HasRows)
            {
                if (reader.Read())
                {
                    User.Instance().Id = reader.GetInt32(0);
                    User.Instance().Imie = reader.GetValue(2).ToString();
                    User.Instance().Nazwisko = reader.GetValue(3).ToString();
                    User.Instance().St_sekretarka = (bool)reader.GetValue(5);
                    User.Instance().St_handlowiec = (bool)reader.GetValue(6);
                    User.Instance().St_subhandlowiec = (bool)reader.GetValue(7);
                    User.Instance().St_kierownik = (bool)reader.GetValue(8);
                    User.Instance().St_dtp = (bool)reader.GetValue(9);
                    User.Instance().St_korekta = (bool)reader.GetValue(10);
                    User.Instance().St_produkcja = (bool)reader.GetValue(11);
                    User.Instance().St_admin = (bool)reader.GetValue(12);
                    if (!reader.IsDBNull(13))
                    {
                        User.Instance().UserAgencyList.Add(new UserAgency(reader.GetInt32(0),
                                                                          reader.GetInt32(13),
                                                                          reader.GetString(14),
                                                                          reader.GetInt32(15)));                        
                    }

                }
                while (reader.Read())
                {
                    if (reader.IsDBNull(13)) continue;

                    User.Instance().UserAgencyList.Add(new UserAgency(reader.GetInt32(0),
                                                  reader.GetInt32(13),
                                                  reader.GetString(14),
                                                  reader.GetInt32(15)));
                }
                conn.Close();
            }
            else
                return false;

            //jezeli handlowiec to sciaga dane agenta

            if (User.Instance().St_handlowiec | User.Instance().St_kierownik | User.Instance().St_subhandlowiec | User.Instance().St_sekretarka)
            {
                command.CommandText = "SELECT A.ID_AGENCJI, A.Symbol, A.F_ROZ, A2.miasto, A2.telefon, A2.fax, A2.Adres_Kor, A2.Symbol, A.InvoiceProviderId FROM AGENCI A ";
                command.CommandText += "LEFT JOIN dbo.AGENCJE A2 ON A.[id_agencji]=A2.[id_agencji] WHERE A.Symbol=@login";

                command.Connection = conn;

                conn.Open();

                reader = command.ExecuteReader();
                if (reader != null)
                    while (reader.Read())
                    {
                        User.Instance().IdAgencji = (int)reader.GetValue(0);
                        User.Instance().Symbol_agenta = reader.GetValue(1).ToString();
                        User.Instance().Kod_agenta = reader.IsDBNull(2) ? "" : reader.GetValue(2).ToString();
                        User.Instance().Miasto = reader.IsDBNull(3) ? "" : reader.GetValue(3).ToString();
                        User.Instance().TelSekretariat = reader.IsDBNull(4) ? "" : reader.GetValue(4).ToString();
                        User.Instance().FaxSekretariat = reader.IsDBNull(5) ? "" : reader.GetValue(5).ToString();
                        User.Instance().AdresBiura = reader.IsDBNull(6) ? "" : reader.GetValue(6).ToString();
                        User.Instance().SymbolAgencji = reader.IsDBNull(7) ? "" : reader.GetValue(7).ToString();
                        User.Instance().InvoiceProviderId = reader.IsDBNull(8) ? 1 : reader.GetInt32(8);
                    }

                conn.Close();
            }

            return true;
        }

        private bool LoginTest()
        {
            sqlBldr.ConnectionString =
                ConfigurationManager.ConnectionStrings[bazyComboBox.SelectedItem.ToString()].ConnectionString;

            sqlBldr.UserID = textBox1.Text;
            sqlBldr.Password = textBox2.Text;
            sqlBldr.ConnectTimeout = 200000;

            SqlConnection conn = new SqlConnection(sqlBldr.ConnectionString);

            try
            {
                conn.Open();
                komunikatLabel.Text = "OK";
                ConnString.getConnString().Value = sqlBldr.ConnectionString;
                conn.Close();
                return true;
            }
            catch (SqlException e1)
            {
                switch (e1.Number)
                {
                    case 18456:
                        komunikatLabel.Text = "Nieprawidłowy login lub hasło";
                        break;
                    default:
                        komunikatLabel.Text = "Brak dostępu do bazy";
                        MessageBox.Show(e1.Message);
                        break;
                }
            }
            return false;
        }

        private void Logowanie_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                button1.PerformClick();
            }
        }

        private static bool SprawdzWersje()
        {
            SqlCommand cmd = new SqlCommand("SELECT TOP 1 current_version FROM Config2");
            cmd.Connection = new SqlConnection(ConnString.getConnString().Value);

            cmd.Connection.Open();
            string ver = (string)cmd.ExecuteScalar();
            cmd.Connection.Close();

            if (ver.Trim() != Application.ProductVersion)
            {
                FormBadVer frm = new FormBadVer();
                frm.labelVer.Text += Application.ProductVersion;
                frm.labelSrvVer.Text += ver;
                frm.ShowDialog();
                return false;
            }

            return true;
        }

        #endregion Methods

        private void cbEnableDbCombo_CheckedChanged(object sender, EventArgs e)
        {
            bazyComboBox.Enabled = cbEnableDbCombo.Checked;
        }
    }
}