using Percent___Qualification_work.Classes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Threading.Tasks;
using Org.BouncyCastle.Asn1.Sec;

namespace Percent___Qualification_work.userControls
{
    public partial class addGame : UserControl
    {
        public List<DataRow> gameData;
        Game existingGame;
        Game newGame;
        api_scrape_game scrape = new api_scrape_game();
        byte[] imageBlob;
        public addGame()
        {
            InitializeComponent();
            gameGenre.DropDownStyle = ComboBoxStyle.DropDownList;
        }

        private async void findGameBtn_Click(object sender, EventArgs e)
        {
            if(gameName.Text == "")
            {
                MessageBox.Show("Please enter the name of the game!");
            }
            else
            {
                string name = gameName.Text;
                existingGame = DatabaseConnection.Instance.GetGame(name);
                if (existingGame != null)
                {
                    // IF the wanted game is in the database then:
                    DialogResult result = MessageBox.Show(existingGame.ToString(), "Confirm game", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == DialogResult.Yes)
                    {
                        // if the game is not in the user list:
                        if (DatabaseConnection.Instance.IsGameInList(Authentication.ActiveUserID, existingGame.Id) == false)
                        {
                            allInputs.Visible = true;
                            gameName.Enabled = false;
                            gameDeveloper.Text = existingGame.Developer;
                            gameDeveloper.Enabled = false;
                            gameGenre.Text = existingGame.Genre;
                            gameGenre.Enabled = false;
                            gameYear.Value = existingGame.ReleaseYear;
                            gameYear.Enabled = false;
                        }
                        // if the game is already in the user's list
                        else MessageBox.Show("This game is already in your list!");
                    }
                }
                else
                {
                    // If the wanted game isn't in the database:
                    MessageBox.Show("Looks like this game isnt in our database. The system will try to export data from intenet. Please wait...");
                    await GetGameFromAPI(gameName.Text);
                    // if the game data was successfully scraped from the API
                    if (newGame != null)
                    {
                        DialogResult result = MessageBox.Show(newGame.ToString(), "Confirm game", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (result == DialogResult.Yes)
                        {
                            backBtn.Visible = true;
                            allInputs.Visible = true;
                            gameName.Enabled = false;
                            gameDeveloper.Text = newGame.Developer;
                            gameDeveloper.Enabled = false;
                            gameGenre.Text = newGame.Genre;
                            gameGenre.Enabled = false;
                            gameYear.Value = newGame.ReleaseYear;
                            gameYear.Enabled = false;
                        }
                        else
                        {
                            MessageBox.Show("Please enter the data manually or try searching again!");
                            EnableInputs();
                            backBtn.Visible = true;
                            allInputs.Visible = true;
                            openFile.Visible = true;
                            imageName.Visible = true;
                        }
                    }
                    else
                    {
                        // if the game data didnt get successfully scraped
                        MessageBox.Show("Looks like we coulnd get the data for the game, please enter manually!");
                        EnableInputs();
                        backBtn.Visible = true;
                        allInputs.Visible = true;
                        openFile.Visible = true;
                        imageName.Visible = true;
                    }
                }
            }
            
        }

        private async Task GetGameFromAPI(string gameName)
        {
            newGame = await scrape.GetGame(gameName);

        }

        private void addGame_Load(object sender, EventArgs e)
        {

        }

        private void openFile_Click(object sender, EventArgs e)
        {

            DialogResult result = coverImageDialog.ShowDialog();

        }

        private void coverImageDialog_FileOk(object sender, CancelEventArgs e)
        {
            string fileName = coverImageDialog.FileName;
            string fileExtension = Path.GetExtension(fileName).ToLower();

            // Check if the file is a PNG or JPG/JPEG
            if (fileExtension == ".png" || fileExtension == ".jpg" || fileExtension == ".jpeg")
            {
                // Convert the image file to a byte array 
                imageBlob = File.ReadAllBytes(fileName);




                // Display only the file name without the path
                string fileOnlyName = Path.GetFileName(fileName);
                imageName.Text = fileOnlyName;
            }
            else
            {
                MessageBox.Show("Please select a valid image file (.png, .jpg, .jpeg).", "Invalid File Type", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true; // Cancel the file selection if the file is not valid
            }
        }

        private void saveGame_Click(object sender, EventArgs e)
        {
            if (existingGame != null)
            {
                int score = Convert.ToInt32(userScore.Value);
                DatabaseConnection.Instance.AddGameToUserList(Authentication.ActiveUserID, existingGame.Id, score);
                MessageBox.Show("Game was successfuly added to your list!");
                ClearInputs();
                CloseWindow();
                existingGame = null;
            }
            else
            {
                if (gameName.Text != "" && gameGenre.Text != "" && gameDeveloper.Text != "" && gameYear.Value != null && imageBlob != null)
                {
                    newGame = new Game(null, gameName.Text, gameGenre.Text, gameDeveloper.Text, Convert.ToInt32(gameYear.Value), imageBlob);
                    DatabaseConnection.Instance.addGameToDB(newGame);
                    newGame = DatabaseConnection.Instance.GetGame(newGame.Name);
                    DatabaseConnection.Instance.AddGameToUserList(Authentication.ActiveUserID, newGame.Id, Convert.ToInt32(userScore.Value));
                    MessageBox.Show("Game was successfuly added to the database and your list!");
                    ClearInputs();
                    CloseWindow();
                    newGame = null;

                }
                else if (newGame != null)
                {
                    DatabaseConnection.Instance.addGameToDB(newGame);
                    newGame = DatabaseConnection.Instance.GetGame(newGame.Name);
                    DatabaseConnection.Instance.AddGameToUserList(Authentication.ActiveUserID, newGame.Id, Convert.ToInt32(userScore.Value));
                    MessageBox.Show("Game was successfuly added to the database and your list!");
                    ClearInputs();
                    CloseWindow();
                    newGame = null;
                }
                else MessageBox.Show("Please fill in all the fields! And don't forget to add a cover image!");
            }

        }

        private void backBtn_Click(object sender, EventArgs e)
        {
            ClearInputs();
            CloseWindow();
        }

        private void ClearInputs()
        {
            gameName.Text = "";
            gameDeveloper.Text = "";
            gameGenre.Text = "";
            gameYear.Value = 1950;
            userScore.Value = 1;
            imageName.Text = "";

        }

        private void CloseWindow()
        {
            allInputs.Visible = false;
            backBtn.Visible = false;
            openFile.Visible = false;
            imageName.Visible = false;
            gameName.Enabled = true;
        }

        public void EnableInputs()
        {
            gameDeveloper.Enabled = true;
            gameGenre.Enabled = true;
            gameYear.Enabled = true;

        }
    }
}
