using MaterialSkin.Controls;
using System;
using System.IO;
using System.Linq;
using System.Media;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace AVS
{
    public partial class LoginForm : MaterialForm
    {
        private MainForm mainForm = null;
        private CartonForm cartonForm = null;
        static ConnectionClass ConnectionClass = new ConnectionClass();
        SoundPlayer soundplayerNew = null;
        private static string SERVER_URL;
        private static string SERVER_LOGIN_URL = "https://cosmos.utopiadeals.com/cosmos/rest/authenticate-user?";
        public static string filePath = "C:\\Users\\Public\\Documents\\AVS\\credentials.txt";
        public static string username;
        public static string password;
        public bool bool_cb_cont = false;


        public LoginForm(Form callingForm, bool val, string value)
        {
            InitializeComponent();

            if (val == true)
            {
                bool_cb_cont = true;
            }

            if (callingForm is MainForm mf)
            {
                mainForm = mf;
                if (mainForm.soundPlayer != null)
                    soundplayerNew = mainForm.soundPlayer;
            }
            else if (callingForm is CartonForm cf)
            {
                cartonForm = cf;
                if (cartonForm.soundPlayer != null)
                    soundplayerNew = cartonForm.soundPlayer;
                
            }
            else
            {
               // fallback player
               // soundplayerNew = new SoundPlayer();
            }

            if (!string.IsNullOrEmpty(value))
            {
                if (value == "LOGIN")
                {
                    lbl_wrong.Visible = false;
                    lbl_login.Visible = true;
                }
                else if (value == "LOGOUT")
                {
                    
                }
                else
                {
                    lbl_wrong.Visible = true;
                    lbl_login.Visible = false;
                    lbl_wrong.Text = "Wrong Shipping Mark";

                }
              
            }
            else
            {
                lbl_wrong.Visible = true;
                lbl_login.Visible = false;
               // lbl_wrong.Text = "Wrong Shipping Mark";
            }

            MaterialSkinClass.ApplySkin(this);
            ControlBox = false;
            SERVER_URL = ConnectionClass.SERVER_URL.ToString();
         
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {
            //this.Activate();
            //this.Focus();

            // If credentials exist, load them
            if (File.Exists(filePath))
            {
                bool success = tryReadCredentials(out username, out password);

                if (success)
                {
                    txt_userName.Text = username;
                    txt_password.Text = password;
                    // btn_login_Click(null, null);
                    if (bool_cb_cont == true)
                    {
                        cb_carton.Checked = true;
                    }
                }
            }
        }

        private void btn_login_Click(object sender, EventArgs e)
        {
            if (soundplayerNew != null)
            {
                soundplayerNew.Stop();
                CloseAlertWindow();
            }
            else
            {
                _ = CheckLoginEndpoint();
            }
        }

        private async Task CheckLoginEndpoint()
        {
            try
            {
                HttpClient client = new HttpClient();
                client.Timeout = TimeSpan.FromMinutes(5);
                string paramater = string.Format("{0}&{1}", "username=" + txt_userName.Text + "", "password=" + txt_password.Text + "");
                var response = await client.GetAsync(string.Format("{0}{1}", SERVER_LOGIN_URL, paramater));
                string responseString = await response.Content.ReadAsStringAsync();

                if (responseString != "Username or password incorrect")
                {

                    if (cb_remember.Checked)
                    {
                        saveCredentials();
                    }

                    if (cb_carton.Checked)
                    {
                        bool_cb_cont = true;
                    }

                    this.Hide();

                    if (mainForm != null)
                    {
                        mainForm.Show(); // restore original MainForm
                    }
                    else if (cartonForm != null)
                    {
                        cartonForm.soundPlayer.Stop(); // stop alarm
                        cartonForm.Show();             // return to CartonForm
                    }
                    else
                    {
                        // fallback if both are null
                        MainForm fallback = new MainForm(txt_userName.Text, bool_cb_cont);
                        fallback.Show();
                    }
                }
                else
                {
                    MessageBox.Show(responseString);
                }
            }
            catch (Exception ex)
            {
                // Handle exception
            }
        }

        private void saveCredentials()
        {
            string username = txt_userName.Text;
            string password = txt_password.Text;

            try
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                using (StreamWriter writer = new StreamWriter(filePath))
                {
                    writer.WriteLine(username);
                    writer.WriteLine(password);
                    //writer.WriteLine(cb_container.Checked);
                    writer.WriteLine(cb_carton.Checked);
                }
            }
            catch (Exception ex)
            {
                // Handle error
            }
        }

        private void CloseAlertWindow()
        {
            DateTime dt = DateTime.Now;
            var openMainForm = Application.OpenForms.OfType<MainForm>().FirstOrDefault();

            if (openMainForm != null)
            {
                openMainForm.ScanTimeText = dt;
                openMainForm.Show();
            }

            this.Close();
        }

        private static bool tryReadCredentials(out string username, out string password)
        {
            username = null;
            password = null;

            try
            {
                if (File.Exists(filePath))
                {
                    string[] lines = File.ReadAllLines(filePath);

                    if (lines.Length >= 2)
                    {
                        username = lines[0];
                        password = lines[1];
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error reading credentials: " + ex.Message);
            }

            return false;
        }

        private void btn_close_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}