using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Newtonsoft.Json.Linq;
namespace WpfApplication19
{
  /// <summary>
  /// Interaction logic for LoginWindow.xaml
  /// </summary>
   

  public partial class LoginWindow : Window
  {
    
	bool _isSkip = true;
    public LoginWindow()
    {
       
      InitializeComponent();
      userIDTextInput.Focus();
    }

    private void button2_Click(object sender, RoutedEventArgs e)
    {
   
		//this.Close();
		this.DialogResult = false;
		Application.Current.MainWindow.Close();

	}

    private void loginButton_Click(object sender, RoutedEventArgs e)
    {
        string data = string.Format("empid={0}&password={1}", userIDTextInput.Text, passwordBox.Password);
        string passwd = passwordBox.Password;
		WebAppConnector wp = new WebAppConnector()
        {
            
            Uri = Utils.getSetting("webServerURL")+"/sessions.json",
            Method = "POST",
            PostData = data
        };
		Response r = null;
		try {
		r = wp.sendRequest();
		}catch{
			if(_isSkip  == false)
				MessageBox.Show("Cannot Send Data to Server, Please Try Again or Get Help from System Administrator");
			//for skip block
			else {
				this.DialogResult = true;
				
				User u = new User();
				u.email = "1234";
				u.empid = "root";
				u.password = "1234";
				u.roles.Add("admin");
				GlobalVars.user = u;

				Application.Current.MainWindow.Show();
				var w = (MainWindow)Application.Current.MainWindow;
				Close();
				return;
			}
		}
        string ans = (string)r.jsonBody["msg"];
        //Console.WriteLine((JArray)r.jsonBody["roles"]);
        
        if (r.status == "OK" && ans == "Y")
        {
			this.DialogResult = true;
			

            User u = new User();
			u.password = passwd;
            u.email = (string)r.jsonBody["email"];
			u.empid = (string)r.jsonBody["empid"];
            foreach (var role in r.jsonBody["roles"])
            {
                u.roles.Add((string)role);
            }
            GlobalVars.user = u;
			Close();
            Application.Current.MainWindow.Show();
			
            var w = (MainWindow)Application.Current.MainWindow;

            //w.UpdateStatus(u);
        }
        else
        {
            alertText.Text = "Your UserID and Password invalid!!";

        }

      
    }
  }
}
