using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Markup;

namespace SdbS.Model
{
    /* Общий класс */
    public class CommonClass
    {
        // Метод возврата соединения к базе данных //
        public static SqlConnection GetConnection()
        {
            string connection = @"Data Source = (LocalDB)\MSSQLLocalDB; 
                                  AttachDbFilename = C:\Users\User\Desktop\DB\ProdStore_Stankovita (last version).mdf; 
                                  Integrated Security = True; Connect Timeout = 30";
            SqlConnection conn = new SqlConnection(connection);
            return conn;
        }
    }

    /*******  MANUFACTURED MACHINES | TYPE MACHINE *******/
    public class Relation_MachinesAndType
    {
        // Метод получения reader`а для обычной генерации ListBox в ManufacturedMachines //
        public static SqlDataReader GetReader_DefaultListBox()
        {
            SqlConnection conn = CommonClass.GetConnection();
            conn.Open();

            SqlCommand cmdSP = new SqlCommand("SP_For_ManufacturedMachines", conn);
            cmdSP.CommandType = System.Data.CommandType.StoredProcedure;
            SqlDataReader reader = cmdSP.ExecuteReader();
            return reader;
        }

        // Метод получения reader'a для ComboBox (поиск) //
        public static SqlDataReader GetReader_ComboBoxSearch(int index)
        {
            SqlConnection conn = CommonClass.GetConnection();
            conn.Open();

            string Expression = $@"SELECT ManufacturedMachines.nameMachine, 
		                                  TypeMachine.name,
		                                  ManufacturedMachines.makingDate
	                                      FROM ManufacturedMachines, TypeMachine
	                                      WHERE ({index} = TypeMachine.typeMachine_ID) AND
                                                ({index} = ManufacturedMachines.typeMachine_ID)";

            SqlCommand cmdExpression = new SqlCommand(Expression, conn);
            SqlDataReader reader = cmdExpression.ExecuteReader();
            return reader;
        }

        // Метод получения reader`a для отображения данных в элементах //
        public static SqlDataReader GetReader_ListBoxSelect(int SelectItem)
        {
            SqlConnection conn = CommonClass.GetConnection();
            conn.Open();

            string Expression = $@"SELECT ManufacturedMachines.nameMachine, 
                                          ManufacturedMachines.photo,
		                                  ManufacturedMachines.typeMachine_ID,
		                                  ManufacturedMachines.makingDate
	                                      FROM ManufacturedMachines
                                          WHERE ({SelectItem} = ManufacturedMachines.machine_ID)";

            SqlCommand cmdExpression = new SqlCommand(Expression, conn);
            SqlDataReader reader = cmdExpression.ExecuteReader();
            return reader;
        }

        // Метод редактирования строки таблицы 'Станки' //
        public static void EditMachine(int type, int index, string name, string date)
        {
            SqlConnection conn = CommonClass.GetConnection();
            conn.Open();

            string Expression = $@"UPDATE ManufacturedMachines SET typeMachine_ID = {type},
                                                                   nameMachine = N'{name}',
                                                                   makingDate = N'{date}'
                                   WHERE (machine_ID = {index})";
             
            SqlCommand cmdExpression = new SqlCommand(Expression, conn);
            cmdExpression.ExecuteNonQuery();
            conn.Close();
        }

        // Метод добавления строки в таблицу 'Станки' //
        public static void AddMachine(int id, int type, string name, string date)
        {
            SqlConnection conn = CommonClass.GetConnection();
            conn.Open();

            string Expression = $@"INSERT INTO ManufacturedMachines(machine_ID, typeMachine_ID, nameMachine, makingDate)
                                   VALUES ({id}, {type}, N'{name}', N'{date}')";

            SqlCommand cmdExpression = new SqlCommand(Expression, conn);
            cmdExpression.ExecuteNonQuery();
            conn.Close();
        }

        // Метод удаления строки из таблицы 'Станки' //
        public static void DeleteMachine(int index)
        {
            SqlConnection conn = CommonClass.GetConnection();
            conn.Open();

            string ExpressionDelete = $@"DELETE FROM ManufacturedMachines
                                         WHERE (machine_ID = {index})";

            SqlCommand cmdExpressionDelete = new SqlCommand(ExpressionDelete, conn);
            cmdExpressionDelete.ExecuteNonQuery();

            conn.Close();
        }

        // Метод изменения изображения у строки в таблице 'Станки' //
        public static void UpdateImage(int ID, string path)
        {
            SqlConnection conn = CommonClass.GetConnection();
            conn.Open();

            string ExpressionUpdate = $@"UPDATE ManufacturedMachines SET photo = N'{path}'
                                         WHERE (machine_ID = {ID})";

            SqlCommand cmdExpressionDelete = new SqlCommand(ExpressionUpdate, conn);
            cmdExpressionDelete.ExecuteNonQuery();

            conn.Close();
        }
    }

    /***** TYPE MACHINES ******/
    public class Metods_TypeMachines
    {
        // Метод получения reader`а для обычной генерации ListBox в TypeMachines //
        public static SqlDataReader GetReader_DefaultListBox()
        {
            SqlConnection conn = CommonClass.GetConnection();
            conn.Open();

            string Expression = "SELECT name FROM TypeMachine";

            SqlCommand cmdExpression = new SqlCommand(Expression, conn);
            SqlDataReader reader = cmdExpression.ExecuteReader();
            return reader;
        }

        // Метод добавления строки в таблицу 'Типы станков' //
        public static void AddType(int id, string name)
        {
            SqlConnection conn = CommonClass.GetConnection();
            conn.Open();

            string Expression = $@"INSERT INTO TypeMachine(typeMachine_ID, name)
                                   VALUES ({id}, N'{name}')";

            SqlCommand cmdExpression = new SqlCommand(Expression, conn);
            cmdExpression.ExecuteNonQuery();
            conn.Close();
        }

        // Метод удаления строки из таблицы 'Типы станков' //
        public static void DeleteType(int index)
        {
            SqlConnection conn = CommonClass.GetConnection();
            conn.Open();

            string ExpressionDelete = $@"DELETE FROM TypeMachine
                                         WHERE (typeMachine_ID = {index})";
            try 
            { 
                SqlCommand cmdExpressionDelete = new SqlCommand(ExpressionDelete, conn);
                cmdExpressionDelete.ExecuteNonQuery();
            } catch (SqlException) {
                MessageBox.Show("Стоп! Вы пытаетесь удалить данные, которые связаны с другой таблицей.",
                                 "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            conn.Close();
        }
    }

    /*** REGISTRATION ***/
    public class RegistrationButton
    {
        public static void AddAccount(string login, string password)
        {
            SqlConnection conn = CommonClass.GetConnection();
            conn.Open();

            string ExpressionAdd = $@"INSERT INTO AuthorizationStorageManager(login, password)
                                      VALUES (N'{login}', N'{password}')";

            SqlCommand cmdExpressionAdd = new SqlCommand(ExpressionAdd, conn);
            cmdExpressionAdd.ExecuteNonQuery();
            conn.Close();
        }
    }
}
