using Contracts.BindingModels;
using Contracts.BusinessLogic;
using Contracts.SearchModel;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Diagnostics;

namespace Forms
{
    public partial class FormCompany : Form
    {
        private readonly ILogger _logger;
        private readonly ICompanyLogic _logic;
        private readonly IStatusLogic _statusLogic;
        private int? _id;
        string[] ModelName = { "Ural1 ", "Vaz2 ", "T3 ", "Mi4 ", "IS5 ", "Mash1 ", "Zavod1 ", "Tech2 ", "Patriot2 ", "Indastris3 " };
        string[] ModelType = { "Mash1 ", "Zavod1 ", "Tech2 ", "Patriot2 ", "Indastris3 ", "Mash21 ", "Zavod21 ", "Tech22 ", "Patriot22 ", "Indastris23 " };
        string[] ModelCat = { "Msk", "DD", "Pet", "Uls", "World" };
        Random rndModel = new Random();
        public int Id { set { _id = value; } }

        public FormCompany(ILogger<FormCompany> logger, ICompanyLogic logic, IStatusLogic statusLogic)
        {
            InitializeComponent();
            _logger = logger;
            _logic = logic;
            _statusLogic = statusLogic;
        }

        private void FormComponent_Load(object sender, EventArgs e)
        {

            try
            {
                var statuses = _statusLogic.ReadList();
                if (statuses != null)
                {
                    StatuscomboBox.DisplayMember = "Title";
                    StatuscomboBox.ValueMember = "Id";
                    StatuscomboBox.DataSource = statuses;
                    StatuscomboBox.SelectedItem = null;
                    if (_id.HasValue)
                    {
                        _logger.LogInformation("Получение company");

                        var view = _logic.ReadElement(new CompanySM
                        {
                            Id = _id.Value
                        });

                        if (view != null)
                        {
                            TitleTextBox.Text = view.Title;
                            
                        }
                    }



                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Ошибка получения company");
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
                MessageBoxIcon.Error);
            }
            
            
        }
       
        private void SaveButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(TitleTextBox.Text))
            {
                MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            _logger.LogInformation("Сохранение компонента");

            try
            {
                var model = new CompanyBM
                {
                    Id = _id ?? 0,
                    Title = TitleTextBox.Text,
                  
                    StatusId = Convert.ToInt32(StatuscomboBox.SelectedValue),
                    StatusTitle = StatuscomboBox.Text,
                };

                var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);

                if (!operationResult)
                {
                    throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
                }

                MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
                DialogResult = DialogResult.OK;
                Close();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Ошибка сохранения компонента");
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ButtonCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        private void StatuscomboBox_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void AddTenbutton_Click(object sender, EventArgs e)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            try
            {
                for (int i = 0; i < 10; i++)
                {
                    var model = new CompanyBM
                    {
                        Id = _id ?? 0,
                        Title = ModelName[rndModel.Next(0, 9)] + ModelType[rndModel.Next(0, 9)] + ModelCat[rndModel.Next(0, 4)],
                        StatusId = rndModel.Next(1, 3),
                        StatusTitle = "",
                    };

                    var operationResult = _logic.Create(model);
                }
                stopwatch.Stop();
                var time = stopwatch.ElapsedMilliseconds;
                Timelabel.Text = time.ToString();
            }catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
           
        }
    }
}