﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Configuration;

namespace Baza_Reklam
{
    public partial class Logowanie : Form
    {

		#region Fields (2) 

        private bool loginResult = false;
        private 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 (textBox1.Text == "") { return; }
            if (textBox2.Text == "") { return; }

            komunikatLabel.Text = "";

            this.Cursor = Cursors.WaitCursor;
            loginResult = loginTest();
            this.Cursor = Cursors.Default;

            if (loginResult)
            {   
                this.Cursor = Cursors.WaitCursor;

                if (sprawdzWersje())
                {
                    if (Login())
                    {
                        this.DialogResult = DialogResult.OK;
                    }
                    else
                    {
                        komunikatLabel.Text = "Konto nieaktywne lub brak uprawnień.";
                    }
                }
                else
                {
                    this.Close();
                    return;
                }
                this.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()
        {
            //textBox1.Text = "krzyzaniak";

            ConnString.getConnString().Value = sqlBldr.ConnectionString;

            SqlConnection conn = new SqlConnection(sqlBldr.ConnectionString);
            
            /*
            Configuration _config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            _config.ConnectionStrings.ConnectionStrings["Baza_Reklam.Properties.Settings.testowe"].ConnectionString = sqlBldr.ConnectionString;

            _config.Save(ConfigurationSaveMode.Modified);

            ConfigurationManager.RefreshSection(_config.ConnectionStrings.SectionInformation.Name);

            Properties.Settings.Default.Reload();
            
             */
             
            //zczytyje prawa uzytkownika
            
            SqlCommand command = new SqlCommand();
            
            command.CommandType = CommandType.Text;
            command.CommandText = "select * from UZYTKOWNICY where LOGIN = @login";
            command.Parameters.AddWithValue("@login", textBox1.Text);
            command.Connection = conn;

            conn.Open();

            SqlDataReader reader = command.ExecuteReader();

            User.getUser().Login = textBox1.Text;
            User.getUser().Password = textBox2.Text;

            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    User.getUser().Imie = reader.GetValue(2).ToString();
                    User.getUser().Nazwisko = reader.GetValue(3).ToString();
                    User.getUser().St_sekretarka = (bool)reader.GetValue(5);
                    User.getUser().St_handlowiec = (bool)reader.GetValue(6);
                    User.getUser().St_subhandlowiec = (bool)reader.GetValue(7);
                    User.getUser().St_kierownik = (bool)reader.GetValue(8);
                    User.getUser().St_dtp = (bool)reader.GetValue(9);
                    User.getUser().St_korekta = (bool)reader.GetValue(10);
                    User.getUser().St_produkcja = (bool)reader.GetValue(11);
                    User.getUser().St_admin = (bool)reader.GetValue(12);
                }
                conn.Close();
            } else
                { return false; }

            //jezeli handlowiec to sciaga dane agenta

            if (User.getUser().St_handlowiec|User.getUser().St_kierownik|User.getUser().St_subhandlowiec|User.getUser().St_sekretarka)
            {
                command.CommandText = "select A.ID_AGENCJI,A.Symbol, A.F_ROZ, A2.miasto, A2.telefon, A2.fax, A2.Adres_Kor,A2.Symbol  from AGENCI ";
                command.CommandText += "as A left join dbo.AGENCJE as A2 on A.[id_agencji]=A2.[id_agencji]  where A.Symbol = @login";
                
                command.Connection = conn;

                conn.Open();

                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    User.getUser().IdAgencji = (int)reader.GetValue(0);
                    User.getUser().Symbol_agenta = reader.GetValue(1).ToString();
                    User.getUser().Kod_agenta = reader.IsDBNull(2) ? "" : reader.GetValue(2).ToString();
                    User.getUser().Miasto = reader.IsDBNull(3) ? "" : reader.GetValue(3).ToString();
                    User.getUser().TelSekretariat = reader.IsDBNull(4) ? "" : reader.GetValue(4).ToString();
                    User.getUser().FaxSekretariat = reader.IsDBNull(5) ? "" : reader.GetValue(5).ToString();
                    User.getUser().AdresBiura = reader.IsDBNull(6) ? "" : reader.GetValue(6).ToString();
                    User.getUser().SymbolAgencji = reader.IsDBNull(7) ? "" : reader.GetValue(7).ToString();
                }

                conn.Close();
            }

            return true;
        }

        private bool loginTest() {

            sqlBldr.ConnectionString= ConfigurationManager.ConnectionStrings[bazyComboBox.SelectedItem.ToString()].ConnectionString;
           
            /*
            sqlBldr.DataSource = Baza_Reklam.Properties.Settings.Default.SERVER;
            sqlBldr.InitialCatalog = Baza_Reklam.Properties.Settings.Default.DATABASE;
            */
        
            sqlBldr.UserID = textBox1.Text;
            sqlBldr.Password = textBox2.Text;
           // sqlBldr.IntegratedSecurity = true;
            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 bool sprawdzWersje()
        {
            SqlCommand cmd = new SqlCommand("SELECT TOP 1 current_version FROM Config2");
            cmd.Connection = new SqlConnection(ConnString.getConnString().Value);

            string ver;

            cmd.Connection.Open();
            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 

     }
}