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 FormCar : Form
    {
        private readonly ILogger _logger;
        private readonly ICarLogic _logic;
        private readonly IStatusLogic _statusLogic;
        private int? _id;
        public int Id { set { _id = value; } }
        string[] ModelName = { "Ural", "Vaz", "T","Min","IS" };
        string[] ModelType = { "V", "34", "Ultra", "Patriot", "30" };
        string[] ModelCat = { "300", "KV", "Cross", "New", "Speed" };
        Random rndModel = new Random();
        public FormCar(ILogger<FormCar> logger, ICarLogic 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("Получение car");

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

                        if (view != null)
                        {
                            ModelTextBox.Text = view.Model;
                            TonnageTextBox.Text = view.Tonnage.ToString();
                        }
                    }



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

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

            try
            {
                var model = new CarBM
                {
                    Id = _id ?? 0,
                    Model = ModelTextBox.Text,
                    number = NumberBox1.Text,
                    Tonnage = Convert.ToInt32(TonnageTextBox.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 TenPlusbutton_Click(object sender, EventArgs e)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            for(int i = 0; i < 10; i++)
            {
                var model = new CarBM
                {
                    Id = _id ?? 0,
                    Model = ModelName[rndModel.Next(0,4)] + ModelType[rndModel.Next(0, 4)] + ModelCat[rndModel.Next(0, 4)],
                    Tonnage = rndModel.Next(30,100),
                    StatusId = rndModel.Next(1,3),
                    StatusTitle = "",
                };

                var operationResult =  _logic.Create(model);
            }
            stopwatch.Stop();
            var time = stopwatch.ElapsedMilliseconds;
            Timelabel.Text = time.ToString();
        }
    }
}