using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApp1;

namespace UWS
{
    public partial class LoginPage : Form
    {
        DataAccessObject dataAccess = new DataAccessObject();
        private string result;
        string UIND_CREDENTIALS_API = "https://portal.utopiaindustries.pk/uind/rest/auth/user";
        public LoginPage()
        {
            this.MaximizeBox = false;
            InitializeComponent();
        }

        private void btn_login_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_username.Text) || string.IsNullOrEmpty(txt_pass.Text))
            {
                MessageBox.Show("Please provide values");
                return;
            }
            else
            {
                CallMethod();

            }
        }

        public async void CallMethod()
        {
            await AuthenticateAsync(txt_username.Text, txt_pass.Text);

        }

        public async Task AuthenticateAsync(string username, string password)
        {
            // Ensure TLS 1.2 is used
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            HttpClient client = new HttpClient();
            client.Timeout = TimeSpan.FromMinutes(5);
            string parameter = string.Format("{0}/{1}", username, password);

            var response = await client.GetAsync($"{UIND_CREDENTIALS_API}/{parameter}");
            string responseString = await response.Content.ReadAsStringAsync();

            //Dictionary<string, string> sData = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseString);
            if (responseString.Equals("NOT FOUND"))
            {
                MessageBox.Show("Incorrect credentials");
                txt_username.Text = "";
                txt_pass.Text = "";
            }
            else
            {
                WeighingForm weighingForm = new WeighingForm(Convert.ToInt32(responseString));
                weighingForm.Show();
                this.Hide();
            }
        }
    }
}
