context: using System;
  using System.Windows.Forms;
  using System.Net;
  using System.Xml.Linq;
  using System.Drawing.Printing;
  using CmsCheckin.Classes;
  using System.Text.RegularExpressions;
  using System.Collections;
  using System.Collections.Generic;
  using System.Collections.Specialized;
  using System.ComponentModel;
  using System.Drawing;
  using Newtonsoft.Json;
  using System.Text;
  
  namespace CmsCheckin
  {
      public partial class LoginSettings : Form, KeyboardInterface
      {
          private static List<WeekDay> weekDays = new List<WeekDay>() {
  			new WeekDay { id = "0", name = "Sunday" },
  			new WeekDay { id = "1", name = "Monday" },
  			new WeekDay { id = "2", name = "Tuesday" },
  			new WeekDay { id = "3", name = "Wednesday" },
  			new WeekDay { id = "4", name = "Thursday" },
  			new WeekDay { id = "5", name = "Friday" },
  			new WeekDay { id = "6", name = "Saturday" }
  		};
  
          private bool CancelClose { get; set; }
  
          private ComboBox currentComboBox = null;
          private TextBox currentTextBox = null;
          private Form keyboard;
  
          private Regex rx = new Regex("\\D");
  
          public LoginSettings()
          {
              InitializeComponent();
  
              DayOfWeekCombo.DataSource = new BindingSource(weekDays, null);
              DayOfWeekCombo.DisplayMember = "Name";
              DayOfWeekCombo.ValueMember = "ID";
              DayOfWeekCombo.SelectedIndex = (int)DateTime.Now.DayOfWeek;
  
              CampusCombo.DataSource = new BindingSource(Program.campusList, null);
              CampusCombo.DisplayMember = "Name";
              CampusCombo.ValueMember = "ID";
  
              SettingsCombo.DataSource = new BindingSource(Program.settingsList, null);
              SettingsCombo.DisplayMember = "Name";
              SettingsCombo.Enter += onComboBoxEnter;
  
              PrintMode.DataSource = new BindingSource(new List<string>(new string[] {
                  "Print To Printer",
                  "Print To Server",
                  "Print From Server",
                  "No Printer"
              }), null);
  
              Building.Enter += onTextboxEnter;
  
              PrintKiosks.Enter += onTextboxEnter;
              KioskName.Enter += onTextboxEnter;
  
              PrinterWidth.Enter += onTextboxEnter;
              PrinterHeight.Enter += onTextboxEnter;
  
              AdminPIN.Enter += onTextboxEnter;
              AdminPINTimeout.Enter += onTextboxEnter;
  
              keyboard = new CommonKeyboard(this);
  
              updateDisplay();
          }
          
          private void onLoginSettingsLoad(object sender, EventArgs e)
          {
              this.CenterToScreen();
              this.Location = new Point(this.Location.X, this.Location.Y / 2);
  
              keyboard.Show();
              attachKeyboard();
  
              var prtdoc = new PrintDocument();
              var defp = prtdoc.PrinterSettings.PrinterName;
              var printerList = new List<string>();
  
              for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
              {
                  printerList.Add(PrinterSettings.InstalledPrinters[i]);
                  Printer.Items.Add(PrinterSettings.InstalledPrinters[i]);
              }
  
              if (printerList.Contains(Program.settings.printer))
              {
                  Printer.SelectedIndex = Printer.FindStringExact(Program.settings.printer);
              }
              else
              {
                  Printer.SelectedIndex = Printer.FindStringExact(defp);
              }
  
              if (!Util.IsDebug())
              {
                  this.Height = 390;
  
                  PrintTest.Enabled = false;
                  FormatLabel.Enabled = false;
                  LabelFormat.Enabled = false;
                  LabelList.Enabled = false;
                  NameLabel.Enabled = false;
                  LoadLabelList.Enabled = false;
                  SaveLabel.Enabled = false;
  
                  PrintTest.Visible = false;
                  FormatLabel.Visible = false;
                  LabelFormat.Visible = false;
                  LabelList.Visible = false;
                  NameLabel.Visible = false;
                  LoadLabelList.Visible = false;
                  SaveLabel.Visible = false;
              }
              else
              {
                  this.Height = 640;
              }
  
              if (PrintMode.Text == "Print From Server")
              {
                  PrintKiosks.Enabled = true;
                  KiosksToPrintForLabel.Enabled = true;
              }
              else
              {
                  PrintKiosks.Enabled = false;
                  KiosksToPrintForLabel.Enabled = false;
              }
  
              attachKeyboard();
          }
  
          private void onLoginSettingsClosing(object sender, FormClosingEventArgs e)
          {
              e.Cancel = CancelClose;
              CancelClose = false;
  
              keyboard.Close();
              keyboard.Dispose();
          }
  
          private void onStartClick(object sender, EventArgs e)
          {
              updateSettings();
              Program.settings.save();
  
              if (Program.settings.buildingMode == true)
              {
                  try
                  {
                      Program.BuildingInfo = Util.FetchBuildingInfo();
  
                      if (Program.BuildingInfo.Activities.Count == 0)
                      {
                          CancelClose = true;
                          return;
                      }
                  }
                  catch (Exception)
                  {
                      MessageBox.Show("Cannot find " + Program.settings.createURL(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                      CancelClose = true;
                  }
              }
  
              if (CancelClose == false && !BuildingAccessMode.Checked)
              {
                  bool bHorizontalCheck = false;
                  bool bVerticalCheck = false;
  
                  if (PrinterWidth.Text.Length == 0) PrinterWidth.Text = "0";
                  if (PrinterHeight.Text.Length == 0) PrinterHeight.Text = "0";
  
                  bHorizontalCheck = int.Parse(PrinterWidth.Text) >= 250;
                  bVerticalCheck = int.Parse(PrinterHeight.Text) >= 51 && int.Parse(PrinterHeight.Text) < 250;
  
                  if (!bHorizontalCheck || !bVerticalCheck)
                  {
                      if (MessageBox.Show("The selected printer page size is not within the usable range.  Labels may not print at all.  Do you want to continue?", "Printer Configuration Error", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                      {
                          CancelClose = true;
                      }
                  }
              }
  
              if (CancelClose == false)
              {
                  DialogResult = DialogResult.OK;
                  this.Hide();
              }
              else
              {
                  CancelClose = false;
              }
          }
  
          private void onPrintTestClick(object sender, EventArgs e)
          {
              Program.settings.printerWidth = PrinterWidth.Text;
              Program.settings.printerHeight = PrinterHeight.Text;
  
              string[] sLabelPieces = LabelList.Text.Split(new char[] { '~' });
  
              if (sLabelPieces.Length >= 2) PrinterHelper.printTestLabel(Printer.Text, LabelFormat.Text);
              else PrinterHelper.printTestLabel(Printer.Text, LabelFormat.Text.Replace("\r\n", ""));
          }
  
          private void onLoadLabelsClick(object sender, EventArgs e)
          {
              string[] labelList = PrinterHelper.fetchLabelList();
  
              if (labelList == null)
              {
                  MessageBox.Show("Could fetch label formats.", "Label List Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                  return;
              }
  
              LabelList.Items.Clear();
              LabelList.Text = "";
              LabelFormat.Text = "";
  
              foreach (var label in labelList)
              {
                  LabelList.Items.Add(label);
              }
  
              MessageBox.Show("Label list load complete!", "Label List", MessageBoxButtons.OK, MessageBoxIcon.Warning);
          }
  
          private void onSaveLabelClick(object sender, EventArgs e)
          {
              string[] sLabelPieces = LabelList.Text.Split(new char[] { '~' });
              if (sLabelPieces.Length > 1)
              {
                  PrinterHelper.saveLabelFormat(sLabelPieces[0], sLabelPieces[1], LabelFormat.Text.Replace("\r\n", ""));
                  LoadLabelList.PerformClick();
              }
          }
  
          private void onFromPrinterClick(object sender, EventArgs e)
          {
              PrinterWidth.Text = PrinterHelper.getPrinterWidth(Printer.Text).ToString();
              PrinterHeight.Text = PrinterHelper.getPrinterHeight(Printer.Text).ToString();
          }
  
          private void onPrinterChanged(object sender, EventArgs e)
          {
              LabelPrinterSize.Text = "Label Size: " + PrinterHelper.getPrinterWidth(Printer.Text) + " X " + PrinterHelper.getPrinterHeight(Printer.Text);
  
              if (Printer.Text.Contains("Datamax"))
              {
                  UseOldDatamaxFormat.Enabled = true;
              }
              else
              {
                  UseOldDatamaxFormat.Enabled = false;
                  UseOldDatamaxFormat.Checked = false;
              }
          }
  
          private void onLabelListChanged(object sender, EventArgs e)
          {
              string[] sLabelPieces = LabelList.Text.Split(new char[] { '~' });
              LabelFormat.Text = PrinterHelper.fetchLabelFormat(sLabelPieces[0], int.Parse(sLabelPieces[1])).Replace("~", "~\r\n");
          }
  
          private void onAdvancedPageSizeChanged(object sender, EventArgs e)
          {
              if (AdvancedPageSize.Checked)
              {
                  PageWidthLabel.Enabled = true;
                  PageHeightLabel.Enabled = true;
  
                  PrinterWidth.Enabled = true;
                  PrinterHeight.Enabled = true;
  
                  SizeFromPrinter.Enabled = true;
  
                  PrinterWidth.Text = "";
                  PrinterHeight.Text = "";
              }
              else
              {
                  PageWidthLabel.Enabled = false;
                  PageHeightLabel.Enabled = false;
  
                  PrinterWidth.Enabled = false;
                  PrinterHeight.Enabled = false;
  
                  SizeFromPrinter.Enabled = false;
  
                  PrinterWidth.Text = "";
                  PrinterHeight.Text = "";
              }
          }
  
          private void onBuildingModeChanged(object sender, EventArgs e)
          {
              if (BuildingAccessMode.Checked)
              {
                  Building.Enabled = true;
                  Building.Text = "";
              }
              else
              {
                  Building.Enabled = false;
                  Building.Text = "";
              }
          }
  
          private void onPrintModeChanged(object sender, EventArgs e)
          {
              var selectedPrintMode = PrintMode.SelectedValue as string;
              if (selectedPrintMode == "Print From Server")
              {
                  PrintKiosks.Enabled = true;
                  KiosksToPrintForLabel.Enabled = true;
  
                  advancedPrinterOptionsGroup.Enabled = true;
                  Printer.Enabled = true;
                  PrinterLabel.Enabled = true;
                  KioskName.Enabled =
                  KioskNameLabel.Enabled = true;
                  labelOptionsGroup.Enabled = true;
  
                  mainOptionsGroup.Enabled = false;
                  buildingOptionsGroup.Enabled = false;
                  askForOptioonsGroup.Enabled = false;
                  otherOptionsGroup.Enabled = false;
                  adminOptionsGroup.Enabled = false;
              }
              else if (selectedPrintMode == "Cloud Printing")
              {
                  advancedPrinterOptionsGroup.Enabled = false;
                  PrintKiosks.Enabled = false;
                  KiosksToPrintForLabel.Enabled = false;
                  Printer.Enabled = false;
                  PrinterLabel.Enabled = false;
                  KioskName.Enabled = 
                  KioskNameLabel.Enabled = true;
                  labelOptionsGroup.Enabled = false;
  
                  mainOptionsGroup.Enabled = true;
                  buildingOptionsGroup.Enabled = true;
                  askForOptioonsGroup.Enabled = true;
                  otherOptionsGroup.Enabled = true;
                  adminOptionsGroup.Enabled = true;
              }
              else if (selectedPrintMode == "No Printer")
              {
                  advancedPrinterOptionsGroup.Enabled = false;
                  PrintKiosks.Enabled = false;
                  KiosksToPrintForLabel.Enabled = false;
                  Printer.Enabled = false;
                  PrinterLabel.Enabled = false;
                  KioskName.Enabled = 
                  KioskNameLabel.Enabled = false;
                  labelOptionsGroup.Enabled = false;
  
                  mainOptionsGroup.Enabled = true;
                  buildingOptionsGroup.Enabled = true;
                  askForOptioonsGroup.Enabled = true;
                  otherOptionsGroup.Enabled = true;
                  adminOptionsGroup.Enabled = true;
              }
              else
              {
                  PrintKiosks.Enabled = false;
                  KiosksToPrintForLabel.Enabled = false;
                  PrintKiosks.Text = "";
  
                  mainOptionsGroup.Enabled = true;
                  buildingOptionsGroup.Enabled = true;
                  askForOptioonsGroup.Enabled = true;
                  otherOptionsGroup.Enabled = true;
                  adminOptionsGroup.Enabled = true;
  
                  advancedPrinterOptionsGroup.Enabled = true;
                  Printer.Enabled = true;
                  PrinterLabel.Enabled = true;
                  KioskName.Enabled = true;
                  KioskNameLabel.Enabled = true;
                  labelOptionsGroup.Enabled = true;
              }
          }
  
          private void onTextboxEnter(object sender, EventArgs e)
          {
              currentTextBox = (TextBox)sender;
              currentComboBox = null;
          }
  
          private void onComboBoxEnter(object sender, EventArgs e)
          {
              currentComboBox = (ComboBox)sender;
              currentTextBox = null;
          }
  
          private void limitNumbersOnly(object sender, EventArgs e)
          {
              TextBox tb = sender as TextBox;
  
              try
              {
  
gt:                 tb.Text = rx.Replace(tb.Text, "");