using System;
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;

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

            bazyComboBox.SelectedIndex = 0;
        }

        #endregion Constructors

        #region Methods (6)

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

            komunikatLabel.Text = string.Empty;

            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()
        {

            SqlConnection conn = null;
            SqlCommand command = null;
            SqlDataReader reader = null;
            try
            {
                ConnString.getConnString().Value = sqlBldr.ConnectionString;

                conn = new SqlConnection(sqlBldr.ConnectionString);

                //zczytyje prawa uzytkownika
                string query = "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 = new SqlCommand(query, conn);
                command.Parameters.AddWithValue("@login", textBox1.Text);

                conn.Open();

                reader = command.ExecuteReader();

                if (reader == null || !reader.HasRows) return false;

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

                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().IsSekretarka = (bool) reader.GetValue(5);
                    User.Instance().IsHandlowiec = (bool) reader.GetValue(6);
                    User.Instance().IsKsiegowosc = (bool) reader.GetValue(7);
                    User.Instance().IsKierownik = (bool) reader.GetValue(8);
                    User.Instance().IsDtp = (bool) reader.GetValue(9);
                    User.Instance().IsKorekta = (bool) reader.GetValue(10);
                    User.Instance().IsProdukcja = (bool) reader.GetValue(11);
                    User.Instance().IsAdmin = (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)));
                }

                //jezeli handlowiec to sciaga dane agenta
                if (User.Instance().IsHandlowiec || User.Instance().IsKierownik || User.Instance().IsSekretarka)
                {
                    reader.Close();
                    reader.Dispose();

                    query = "SELECT A.ID_AGENCJI, A.Symbol, A.F_ROZ, A2.miasto, A2.telefon, A2.fax, A2.Adres_Kor, A2.Symbol, A.InvoiceProviderId, A.Aktywny FROM AGENCI A "
                            + "LEFT JOIN dbo.AGENCJE A2 ON A.[id_agencji]=A2.[id_agencji] WHERE A.Symbol=@login";
                    
                    command.CommandText = query;

                    reader = command.ExecuteReader();

                    if (reader == null || !reader.HasRows) return true;

                    bool isAgentActive = true;

                    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);
                        isAgentActive = reader.GetBoolean(9);
                    }

                    return isAgentActive;
                }

                return true;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
                if (command != null) command.Dispose();

                if (conn != null)
                {
                    conn.Close();
                    conn.Dispose();
                }

                //reset cursor - just in case...
                Cursor = Cursors.Default;
                //set user name to see it on Error Log Report
                User.Instance().Login = textBox1.Text;
            }
        }

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

            sqlBldr.UserID = textBox1.Text;
            sqlBldr.Password = textBox2.Text;
            sqlBldr.ConnectTimeout = 200000;
            sqlBldr.ApplicationName = "BazaReklam_v" + Application.ProductVersion;

            SqlConnection conn = new SqlConnection(sqlBldr.ConnectionString);

            try
            {
                conn.Open();
                komunikatLabel.Text = "OK";
                ConnString.getConnString().Value = sqlBldr.ConnectionString;
                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;
                }
            }
            finally
            {
                conn.Close(); 
            }
            return false;
        }

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

        private static bool SprawdzWersje()
        {
            SqlCommand cmd = null;
            try
            {
                cmd = new SqlCommand("SELECT ver FROM dbo.app WHERE [name]='BazaReklam'");
                cmd.Connection =
                    new SqlConnection("Data Source=" + ConnString.GetDataSource() + ";Initial Catalog=Applications;Persist Security Info=True;User=updater;Password=UpdateSolution;Application Name=BazaReklam_v" + Application.ProductVersion + ";");
                

                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;
                }
            }
            finally
            {
                if (cmd != null)
                {
                    if (cmd.Connection != null)
                    {
                        cmd.Connection.Close();
                        cmd.Connection.Dispose();
                    }
                    cmd.Dispose();
                }
            }

            return true;
        }

        #endregion Methods

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