using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace mateo
{
    public partial class SysAdmin : Window
    {
        byte[] image; //очищать!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        int idattraction = 0;
        int idemployees = 0;
        public SysAdmin()
        {
            InitializeComponent();
            var fio = DB.GetContext().Employees.FirstOrDefault(x => x.IDEmployees == DB.Idemployees);
            txtFio_Admin.Text = DB.GetContext().Role.FirstOrDefault(x => x.IDRole == fio.FKRole).Role1 + "\n" + fio.LastName + " " + fio.FirstName + " " + fio.MiddleName;

            datagridAttraction.ItemsSource = DB.GetContext().Attraction.ToList();
            datagridEmployees.ItemsSource = DB.GetContext().Employees.Where(x => x.IDEmployees != DB.Idemployees).ToList();
            comboboxChange_StatusAttraction.ItemsSource = comboboxStatus_Attraction.ItemsSource = DB.GetContext().StatusAttraction.ToList();
            comboboxChange_TypeAttraction.ItemsSource = comboboxType_Attraction.ItemsSource = DB.GetContext().Type.ToList();

            if(fio.FKRole == 2) //если простто админ скрываем доб сотрудников/ может проверять не по id
            tabEmployees.Visibility = Visibility.Hidden;
        }

        #region attraction
        private void BtnAddImage(object sender, RoutedEventArgs e)
        {
            //выбираем и выводим изображение в image_add_attraction
            string imageLoc;
            OpenFileDialog dld = new OpenFileDialog();
            dld.Filter = "JPG Files (*.jpg)|*.jpg|PNG Files (*.png)|*.png|JPEG Files (*.jpeg)|*.jpeg";
            dld.Title = "Выберите изображение пользователя";
            bool? result = dld.ShowDialog();
            if (result == true)
            {
                imageLoc = dld.FileName;
                imageAdd_Attraction.Source = new BitmapImage(new Uri(imageLoc));
                FileStream fs = new FileStream(imageLoc, FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);
                image = br.ReadBytes((int)fs.Length);
            }
        }

        private void BtnAddAttractionClick(object sender, RoutedEventArgs e)
        {
            //добавляем новый аттракцион в бд
            if (txtName_Attraction.Text != "" && txtDescription_Attraction.Text != "" && txtQuantity_Attraction.Text != "" && txtPriceOld_Attraction.Text != "" && txtPriceBaby_Attraction.Text != ""
                && imageAdd_Attraction.Source != null && comboboxStatus_Attraction.Text != "" && comboboxType_Attraction.Text != "")
            {
                var status = DB.GetContext().StatusAttraction.Where(x => x.StatusAttraction1 == comboboxStatus_Attraction.Text).FirstOrDefault();
                var type = DB.GetContext().Type.Where(x => x.Type1 == comboboxType_Attraction.Text).FirstOrDefault();
                Attraction attraction = new Attraction
                {
                    NameAttraction = txtName_Attraction.Text,
                    Description = txtDescription_Attraction.Text,
                    QuantityAttraction = Convert.ToInt32(txtQuantity_Attraction.Text),
                    PriceOld = Convert.ToDecimal(txtPriceOld_Attraction.Text),
                    PriceBaby = Convert.ToDecimal(txtPriceBaby_Attraction.Text),
                    ImageAttraction = image,
                    FKEmployees = DB.Idemployees,
                    FKStatusAttraction = status.IDStatusAttraction,
                    FKType = type.IDType
                };
                DB.GetContext().Attraction.Add(attraction);
                DB.GetContext().SaveChanges();

                MessageBox.Show("dcscsd");
                datagridAttraction.ItemsSource = DB.GetContext().Attraction.ToList();
                gridAddAttraction.Visibility = Visibility.Hidden;
            }
            else MessageBox.Show("Пустые поля!");
        }
        private void BtnChangeAttractionClick(object sender, RoutedEventArgs e)
        {
            //выводим данные из datagrid в grid чтобы потом изменить
            if(datagridAttraction.SelectedItem is Attraction attraction)
            {
                idattraction = attraction.IDAttraction;
                txtChange_NameAttraction.Text = attraction.NameAttraction;
                txtChange_Description.Text = attraction.Description;
                txtChange_Quantity.Text = attraction.QuantityAttraction.ToString();

                decimal price = Convert.ToDecimal(attraction.PriceOld);
                txtChange_PriceOldAttraction.Text = String.Format("{0:0.00}", price);
                price = Convert.ToDecimal(attraction.PriceBaby);
                txtChange_PriceBabyAttraction.Text = String.Format("{0:0.00}", price);

                comboboxChange_StatusAttraction.Text = attraction.StatusAttraction.StatusAttraction1;
                comboboxChange_TypeAttraction.Text = attraction.Type.Type1;

                image = attraction.ImageAttraction;
                MemoryStream ms = new MemoryStream(image);
                imageChange_Attraction.Source = BitmapFrame.Create(ms);
                datagridAttraction.Visibility = Visibility.Hidden;

                gridChangeAttraction.Visibility = Visibility.Visible;
            }
        }
        private void BtnSaveChangeClick(object sender, RoutedEventArgs e)
        {
            if (txtChange_NameAttraction.Text != "" && txtChange_Description.Text != "" && txtChange_Quantity.Text != "" && txtChange_PriceOldAttraction.Text != "" && txtChange_PriceBabyAttraction.Text != ""
               && imageChange_Attraction.Source != null && comboboxChange_StatusAttraction.Text != "" && comboboxChange_TypeAttraction.Text != "")
            {
                //вносим изменения из change_attraction_grid в бд
                var attr = DB.GetContext().Attraction.Where(x => x.IDAttraction == idattraction).FirstOrDefault();
                var type = DB.GetContext().Type.Where(x => x.Type1 == comboboxChange_TypeAttraction.Text).FirstOrDefault();


                attr.NameAttraction = txtChange_NameAttraction.Text;
                attr.Description = txtChange_Description.Text;
                attr.QuantityAttraction = Convert.ToInt32(txtChange_Quantity.Text);
                attr.PriceOld = Convert.ToDecimal(txtChange_PriceOldAttraction.Text);
                attr.PriceBaby = Convert.ToDecimal(txtChange_PriceBabyAttraction.Text);
                //ищем в таблице StatusAttraction столбец с нужным статусом, затем записываем его id в FKStatusAttraction таблицы Attraction
                var status = DB.GetContext().StatusAttraction.Where(x => x.StatusAttraction1 == comboboxChange_StatusAttraction.Text).FirstOrDefault();
                attr.FKStatusAttraction = status.IDStatusAttraction;

                attr.FKType = type.IDType; 

                attr.ImageAttraction = image;
                DB.GetContext().SaveChanges();
                MessageBox.Show("4444444444444444");

                gridChangeAttraction.Visibility = Visibility.Hidden;
                datagridAttraction.Visibility = Visibility.Visible;
                datagridAttraction.ItemsSource = DB.GetContext().Attraction.ToList();
            }
            else MessageBox.Show("Пустые поля!");
        }

        private void BtnBackAttractionClick(object sender, RoutedEventArgs e)
        {
            gridAddAttraction.Visibility = Visibility.Hidden;
            gridChangeAttraction.Visibility = Visibility.Hidden;
            datagridAttraction.Visibility = Visibility.Visible;
        }

        private void BtnChangeImageClick(object sender, RoutedEventArgs e)
        {
            //выбираем и выводим изображение в image_change_attraction
            string imageLoc;
            OpenFileDialog dld = new OpenFileDialog();
            dld.Filter = "JPG Files (*.jpg)|*.jpg|PNG Files (*.png)|*.png|JPEG Files (*.jpeg)|*.jpeg";
            dld.Title = "Выберите изображение пользователя";
            bool? result = dld.ShowDialog();
            if (result == true)
            {
                imageLoc = dld.FileName;
                imageChange_Attraction.Source = new BitmapImage(new Uri(imageLoc));
                FileStream fs = new FileStream(imageLoc, FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);
                image = br.ReadBytes((int)fs.Length);
            }
        }

        private void BtnAddNewAttractionClick(object sender, RoutedEventArgs e)
        {
            gridAddAttraction.Visibility = Visibility.Visible;
        }
        #endregion

        private void BtnExit(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();

        }

        private void BtnChangeEmployeesClick(object sender, RoutedEventArgs e)
        {
            //выводим данные из datagrid в grid чтобы потом изменить
            if (datagridEmployees.SelectedItem is Employees employees)
            {
                idemployees = employees.IDEmployees;
                datagridEmployees.Visibility = Visibility.Hidden;
                gridChangeEmployees.Visibility = Visibility.Visible;
                txtLastName_ChangeEmployyes.Text = employees.LastName;
                txtFirstName_ChangeEmployyes.Text = employees.FirstName;
                txtMiddleName_ChangeEmployees.Text = employees.MiddleName;
                comboboxRole_ChangeEmployees.Text = employees.Role.Role1;
                comboboxStatus_ChangeEmployees.Text = employees.StatusEmployees.StatusEmployees1;
            }
        }

        private void BtnAddEmployeesClick(object sender, RoutedEventArgs e)
        {
            //добавляем нового администратора в бд
            if (txtLastName_Employyes.Text != "" && txtFirstName_Employyes.Text != "" && 
                comboboxRole_Employees.Text != "" && comboboxStatus_Employees.Text != "")
            {
                var idemployees = DB.GetContext().Employees.OrderByDescending(x => x.IDEmployees).FirstOrDefault();
                string login = "admin" + (idemployees.IDEmployees + 1).ToString();

                Random random = new Random();
                int pass1 = random.Next(100,999);
                var list = new List<string> { "a", "b", "c", "d", "e" };
                int index = random.Next(list.Count);
                int index1 = random.Next(list.Count);
                int index2 = random.Next(list.Count);
                int index3 = random.Next(list.Count);

                string password = list[index] + list[index1] + pass1 + list[index2] + list[index3];
                var status = DB.GetContext().StatusEmployees.Where(x => x.StatusEmployees1 == comboboxStatus_Employees.Text).FirstOrDefault();
                var role = DB.GetContext().Role.Where(x => x.Role1 == comboboxRole_Employees.Text).FirstOrDefault();
                Employees employees = new Employees
                {
                    LastName = txtLastName_Employyes.Text,
                    FirstName = txtFirstName_Employyes.Text,
                    MiddleName = txtMiddleName_Employees.Text,
                    Login = login,
                    Password = password,
                    FKRole = role.IDRole,
                    FKStatusEmployees = status.IDStatusEmployees
                };
                DB.GetContext().Employees.Add(employees);
                DB.GetContext().SaveChanges();
                MessageBox.Show("Сотрудник добавлен", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);

                datagridEmployees.ItemsSource = DB.GetContext().Employees.Where(x => x.IDEmployees != DB.Idemployees).ToList();
                gridAddEmployees.Visibility = Visibility.Hidden;
            }
            else MessageBox.Show("Пустые поля!");
        }
        private void BtnBackEmployeesClick(object sender, RoutedEventArgs e)
        {
            gridAddEmployees.Visibility = Visibility.Hidden;
            datagridEmployees.Visibility = Visibility.Visible;
            gridChangeEmployees.Visibility = Visibility.Hidden;
        }

        private void BtnAddNewEmployeesClick(object sender, RoutedEventArgs e)
        {
            gridAddEmployees.Visibility = Visibility.Visible;
        }

        private void BtnSaveChangeEmployeesClick(object sender, RoutedEventArgs e)
        {
            if (txtLastName_ChangeEmployyes.Text != "" && txtFirstName_ChangeEmployyes.Text != "" &&
                 comboboxRole_ChangeEmployees.Text != "" && comboboxStatus_ChangeEmployees.Text != "")
            {
                //вносим изменения из gridChangeEmployees в бд
                var attr = DB.GetContext().Employees.Where(x => x.IDEmployees == idemployees).FirstOrDefault();

                attr.LastName = txtLastName_ChangeEmployyes.Text;
                attr.FirstName = txtFirstName_ChangeEmployyes.Text;
                attr.MiddleName = txtMiddleName_ChangeEmployees.Text;

                //ищем в таблице StatusEmployees столбец с нужным статусом, затем записываем его id в FKStatusEmployees таблицы Employees
                var status = DB.GetContext().StatusEmployees.Where(x => x.StatusEmployees1 == comboboxStatus_ChangeEmployees.Text).FirstOrDefault();
                attr.FKStatusEmployees = status.IDStatusEmployees;
                var role = DB.GetContext().Role.Where(x => x.Role1 == comboboxRole_ChangeEmployees.Text).FirstOrDefault();
                attr.FKRole = role.IDRole;


                DB.GetContext().SaveChanges();

                MessageBox.Show("Изменения сохранены");

                gridChangeEmployees.Visibility = Visibility.Hidden;
                datagridEmployees.Visibility = Visibility.Visible;
                datagridEmployees.ItemsSource = DB.GetContext().Employees.Where(x => x.IDEmployees != DB.Idemployees).ToList();
            }
            else MessageBox.Show("Пустые поля!");
        }

        private void btnLogout(object sender, RoutedEventArgs e)
        { 
            First first = new First();
            first.Show();
            this.Close();
        }

        //private void txtPassword_TextChanged(object sender, TextChangedEventArgs e)
        //{
        //    passPassword.Password = txtPassword.Text;
        //}

        //private void PasswordBoxInVisible(object sender, RoutedEventArgs e)
        //{
        //    imgInVisible.Visibility = Visibility.Visible;
        //    imgVisible.Visibility = Visibility.Hidden;
        //    txtPassword.Visibility = Visibility.Visible;
        //    txtPassword.Text = passPassword.Password;
        //    passPassword.Visibility = Visibility.Hidden;
        //}

        //private void PasswordBoxVisible(object sender, RoutedEventArgs e)
        //{
        //    //показать
        //    imgVisible.Visibility = Visibility.Visible;
        //    imgInVisible.Visibility = Visibility.Hidden;
        //    txtPassword.Visibility = Visibility.Hidden;
        //    passPassword.Visibility = Visibility.Visible;
        //}
    }
}
