using Npgsql;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TestsManipulate
{
    public partial class AddResult : Form
    {
        private MainPage _mainPage;
        public AddResult(MainPage mainPage)
        {
            InitializeComponent();
            _mainPage = mainPage;
            LoadTitles();
            LoadLogins();
        }

        private void AddResultButton(object sender, EventArgs e)
        {
            var conn = new NpgsqlConnection(Program.connString);
            conn.Open();
            var cmd = new NpgsqlCommand(
                "call add_new_result(@test_id, @user_id, @score, @max_score, @user_login)", conn);
            cmd.Parameters.AddWithValue("test_id", Convert.ToInt32(comboBox1.SelectedValue));
            cmd.Parameters.AddWithValue("user_id", Convert.ToInt32(comboBox2.SelectedValue));
            cmd.Parameters.AddWithValue("score", Convert.ToInt32(textBox1.Text));
            cmd.Parameters.AddWithValue("max_score", Convert.ToInt32(textBox2.Text));
            cmd.Parameters.AddWithValue("user_login", Program.login);

            cmd.ExecuteNonQuery();

            MessageBox.Show("Запись успешно добавлена", "Успешно");
            _mainPage.LoadResults();

            this.Close();

        }

        private void LoadTitles()
        {
            var conn = new NpgsqlConnection(Program.connString);
            conn.Open();
            var cmd = new NpgsqlCommand(
                "SELECT id, title FROM tests ORDER BY title", conn);
            var reader = cmd.ExecuteReader();

            comboBox1.DisplayMember = "title";
            comboBox1.ValueMember = "id";

            var dt = new DataTable();
            dt.Load(reader);
            comboBox1.DataSource = dt;

            
        }

        private void LoadLogins()
        {
            var conn = new NpgsqlConnection(Program.connString);
            conn.Open();
            var cmd = new NpgsqlCommand(
                "SELECT id, login FROM users ORDER BY login", conn);
            var reader = cmd.ExecuteReader();

            comboBox2.DisplayMember = "login";
            comboBox2.ValueMember = "id";

            var dt = new DataTable();
            dt.Load(reader);
            comboBox2.DataSource = dt;
        }

    }
}
