/// <summary>
 /// Method that allow access to the class
 /// </summary>
 /// <returns>Instance of the class ListOfCards</returns>
 public static ListOfCards GetInstance()
 {
     if (_instance == null)
     {
         _instance = new ListOfCards();
     }
     return(Instance);
 }
 /// <summary>
 /// This method initializes the different classes and data
 /// </summary>
 private void InitializesClassesData()
 {
     ServoMotor.GetInstance().Lock();
     RFIDReader.GetInstance();
     DisplayLoad();
     ListOfCards.GetInstance().CardsList = SDCard.GetInstance().LoadCards();
     if (ListOfCards.GetInstance().CardsList == null)
     {
         ListOfCards.GetInstance().CardsList = new ArrayList();
     }
     RestoreInitialState();
 }
        /// <summary>
        /// When the menu to display all cards is selected
        /// </summary>
        private void DisplayCards()
        {
            switch (_displayCardsState)
            {
            case DISPLAY_CARDS_STATE.listIsEmpty:
                LCD.GetInstance().Clear();
                if (ListOfCards.GetInstance().IsEmpty())
                {
                    _displayCardsState = DISPLAY_CARDS_STATE.errorMSG;
                }
                else
                {
                    _displayCardsState = DISPLAY_CARDS_STATE.displayAllCards;
                }
                break;

            case DISPLAY_CARDS_STATE.errorMSG:
                LCD.GetInstance().DisplayText(GT.Color.Red, "/!\\ Aucun badge n'est enregistre /!\\", 10, LCD.GetInstance().LcdHeight / 2);
                Thread.Sleep(2000);
                RestoreInitialState();
                break;

            case DISPLAY_CARDS_STATE.displayAllCards:
                int positionY = 10;     // The Y position on the LCD
                LCD.GetInstance().DisplayText(GT.Color.Gray, "Pour quitter, appuyer sur le joystick", 10, LCD.GetInstance().LcdHeight - 20);

                foreach (Card card in ListOfCards.GetInstance().CardsList)
                {
                    LCD.GetInstance().DisplayText(GT.Color.Black, card.Name, 10, positionY);
                    positionY += 15;     // Increment the Y position
                }

                if (!_joystickButton.Read())     // If joystick button is press
                {
                    RestoreInitialState();
                }
                break;

            default:
                _displayCardsState = DISPLAY_CARDS_STATE.listIsEmpty;
                break;
            }
        }
        public static void Main()
        {
            Debug.Print(Resources.GetString(Resources.StringResources.String1));

            AnalogInput joystick_y = new AnalogInput(FEZSpider.Socket9.AnalogInput4); //Initialise l'axe Y par rapport à l'orientation de mon joystick

            _reader.IdReceived          += _reader_IdReceived;
            _reader.MalformedIdReceived += _reader_MalformedIdReceived;

            ListOfCards.GetInstance().AddCardToList("Badge", "U1 2D 34 56 FC");
            ListOfCards.GetInstance().AddCardToList("Badge", "U9 65 B2 3C F5");
            ListOfCards.GetInstance().AddCardToList("Badge", "U1 2D 34 56 FC");
            ListOfCards.GetInstance().AddCardToList("Badge", "U9 65 B2 3C F5");
            ListOfCards.GetInstance().AddCardToList("Badge", "U1 2D 34 56 FC");
            ListOfCards.GetInstance().AddCardToList("Badge", "U9 65 B2 3C F5");
            ListOfCards.GetInstance().AddCardToList("Marty", "U1 2D 34 56 FC");
            ListOfCards.GetInstance().AddCardToList("Professeur", "U9 65 B2 3C F5");

            //SDCardSerializer.GetInstance().SerializecCardsToSDCard(ListOfCards.GetInstance().CardsList);
            //SDCardSerializer.GetInstance().showDirectory();
            //RFIDReader.GetInstance();
            ServoMotor.GetInstance();

            while (true)
            {
                Debug.Print(joystick_y.Read().ToString());
                if (joystick_y.Read() == 1)
                {
                    ServoMotor.GetInstance().Unlock();
                }
                else if (joystick_y.Read() == 0)
                {
                    ServoMotor.GetInstance().Lock();
                }
            }
        }
        /// <summary>
        /// When the menu to delete a card is selected
        /// </summary>
        private void DeleteCard()
        {
            switch (_deleteCardState)
            {
            case DELETE_CARD_STATE.listIsEmpty:
                LCD.GetInstance().Clear();
                if (ListOfCards.GetInstance().IsEmpty())
                {
                    LCD.GetInstance().DisplayText(GT.Color.Red, "/!\\ Aucun badge n'est enregistre /!\\", 10, LCD.GetInstance().LcdHeight / 2);
                    Thread.Sleep(2000);
                    RestoreInitialState();
                }
                else
                {
                    _deleteCardState = DELETE_CARD_STATE.selectCard;
                }
                break;

            case DELETE_CARD_STATE.selectCard:
                int positionY = 10;     // The Y position on the LCD
                int i         = 0;
                foreach (Card card in ListOfCards.GetInstance().CardsList)
                {
                    if (LCDTextFields.CursorPosition == i)     // If the cursorposition is at this char
                    {
                        LCD.GetInstance().DisplayText(GT.Color.Blue, card.Name, 10, positionY);
                    }
                    else
                    {
                        LCD.GetInstance().DisplayText(GT.Color.Black, card.Name, 10, positionY);
                    }
                    positionY += 15;     // Increment the Y position
                    i++;
                }
                LCD.GetInstance().DisplayText(GT.Color.Gray, "Pour selectionner le badge, appuyer sur le joystick", 10, LCD.GetInstance().LcdHeight - 30);

                if (_joystickX.Read() > JOYSTICK_DOWN_LEFT)                                           // If joystick is down
                {
                    LCDTextFields.CursorPosition++;                                                   // Move the cursor to the next name
                    if (LCDTextFields.CursorPosition > ListOfCards.GetInstance().CardsList.Count - 1) // If the cursor get out of the range of the list of cards array
                    {
                        LCDTextFields.CursorPosition = 0;                                             // Move to the first position of the list of cards array
                    }
                    Thread.Sleep(100);                                                                // Wait 0.1 second to prevent the cursor from moving too fast
                }
                else if (_joystickX.Read() < JOYSTICK_UP_RIGHT)                                       // If joystick is up
                {
                    LCDTextFields.CursorPosition--;                                                   // Move the cursor to the previous name
                    if (LCDTextFields.CursorPosition < 0)                                             // If the cursor get out of the range of the list array
                    {
                        LCDTextFields.CursorPosition = ListOfCards.GetInstance().CardsList.Count - 1; // Move to the last position of the list of cards array
                    }
                    Thread.Sleep(100);                                                                // Wait 0.1 second to prevent the cursor from moving too fast
                }
                if (!_joystickButton.Read())                                                          // If joystick button is press
                {
                    _deleteCardState = DELETE_CARD_STATE.save;
                }
                break;

            case DELETE_CARD_STATE.save:
                try
                {
                    ListOfCards.GetInstance().DeleteCardFromList(LCDTextFields.CursorPosition);
                    SDCard.GetInstance().SaveCards(ListOfCards.GetInstance().CardsList);
                    _deleteCardState = DELETE_CARD_STATE.success;
                }
                catch (Exception e)
                {
                    _deleteCardState = DELETE_CARD_STATE.errorMSG;
                }
                break;

            case DELETE_CARD_STATE.errorMSG:
                DisplayError();
                Thread.Sleep(2000);
                RestoreInitialState();
                break;

            case DELETE_CARD_STATE.success:
                DisplaySave();
                LCD.GetInstance().DisplayText(GT.Color.Green, "Le badge a bien ete supprime", 10, LCD.GetInstance().LcdHeight / 2);
                Thread.Sleep(2000);
                RestoreInitialState();
                break;

            default:
                _deleteCardState = DELETE_CARD_STATE.listIsEmpty;
                break;
            }
        }
        /// <summary>
        /// When the menu to add a card is selected
        /// </summary>
        private void AddCard()
        {
            switch (_addCardState)
            {
            case ADD_CARD_STATE.waitRFID:
                LCD.GetInstance().Clear();
                LCD.GetInstance().DisplayText(GT.Color.Gray, "Veuillez approcher un badge du lecteur");
                if (RFIDReader.GetInstance().IsBadgeScan)
                {
                    _addCardState = ADD_CARD_STATE.RFIDDetected;
                    LCD.GetInstance().DisplayText(GT.Color.Green, "Votre badge a ete correctement scanne", 10, LCD.GetInstance().LcdHeight / 2);
                    Thread.Sleep(2000);     // Wait 2 seconds to see the message
                }
                break;

            case ADD_CARD_STATE.RFIDDetected:
                LCD.GetInstance().Clear();
                string uid = RFIDReader.GetInstance().CurrentUid;

                if (ListOfCards.GetInstance().FindCardInlist(uid))     // If the badge scanned already exist
                {
                    _addCardState = ADD_CARD_STATE.badgeExist;
                }
                else
                {
                    _addCardState = ADD_CARD_STATE.bageDontExist;
                }
                break;

            case ADD_CARD_STATE.badgeExist:
                LCD.GetInstance().DisplayText(GT.Color.Red, "/!\\ Erreur : Ce badge est deja sauvegarde /!\\", 10, LCD.GetInstance().LcdHeight / 2);
                Thread.Sleep(2000);     // Wait 2 seconds to see the message
                RestoreInitialState();
                break;

            case ADD_CARD_STATE.bageDontExist:
                string name      = LCDTextFields.Content; // The content value of the LCD field, it's the name of the badge
                char[] charArray = name.ToCharArray();    // We split the name in a char array to make it easier to modify char by char
                int    x         = 110;                   // The position index where we're gonna write the first char

                if (LCDTextFields.ShouldBeRefresh)        // If we need to refresh because we have modify a char or the position of the cursor
                {
                    LCD.GetInstance().Clear();
                    LCD.GetInstance().DisplayText(GT.Color.Gray, "Votre badge :", 10, LCD.GetInstance().LcdHeight / 2);
                    LCD.GetInstance().DisplayText(GT.Color.Gray, "Pour valider le nom, appuyer sur le joystick", 10, LCD.GetInstance().LcdHeight - 20);
                    for (int i = 0; i < charArray.Length; i++)
                    {
                        if (i == LCDTextFields.CursorPosition)     // If the cursorposition is at this char
                        {
                            LCD.GetInstance().DisplayText(GT.Color.Blue, charArray[i].ToString(), x, LCD.GetInstance().LcdHeight / 2);
                        }
                        else
                        {
                            LCD.GetInstance().DisplayText(GT.Color.Black, charArray[i].ToString(), x, LCD.GetInstance().LcdHeight / 2);
                        }
                        x += 10;     // Increment the X position on the LCD
                    }
                    LCDTextFields.ShouldBeRefresh = false;
                }

                if (_joystickX.Read() < JOYSTICK_UP_RIGHT)       // If the joystick is up
                {
                    charArray[LCDTextFields.CursorPosition]++;   // Increment the char ex : A -> B
                    LCDTextFields.ShouldBeRefresh = true;
                    Thread.Sleep(100);                           // Wait 0.1 second to prevent the letter from scrolling too fast
                }
                else if (_joystickX.Read() > JOYSTICK_DOWN_LEFT) // If the joystick is down
                {
                    charArray[LCDTextFields.CursorPosition]--;   // ecrement the char ex : B -> A
                    LCDTextFields.ShouldBeRefresh = true;
                    Thread.Sleep(100);                           // Wait 0.1 second to prevent the letter from scrolling too fast
                }


                if (_joystickY.Read() < JOYSTICK_UP_RIGHT)                   // If the joystick is right
                {
                    LCDTextFields.CursorPosition++;                          // Move the cursor to the next char
                    if (LCDTextFields.CursorPosition > charArray.Length - 1) // If the cursor get out of the range of the char array
                    {
                        LCDTextFields.CursorPosition = 0;                    // Move to the first position of the char array
                    }
                    LCDTextFields.ShouldBeRefresh = true;
                    Thread.Sleep(200);                                       // Wait 0.2 seconds to prevent the cursor from moving too fast
                }
                else if (_joystickY.Read() > JOYSTICK_DOWN_LEFT)             // If the joystick is left
                {
                    LCDTextFields.CursorPosition--;                          // Move the cursor to the previous char
                    if (LCDTextFields.CursorPosition < 0)                    // If the cursor get out of the range of the char array
                    {
                        LCDTextFields.CursorPosition = charArray.Length - 1; // Move to the last position of the char array
                    }
                    LCDTextFields.ShouldBeRefresh = true;
                    Thread.Sleep(200);     // Wait 0.2 seconds to prevent the cursor from moving too fast
                }

                LCDTextFields.Content = new string(charArray); // Set the LCD text field with the value of the modify char array

                if (!_joystickButton.Read())                   // If joystick button is press
                {
                    _addCardState = ADD_CARD_STATE.save;
                }
                break;

            case ADD_CARD_STATE.save:
                try
                {
                    uid  = RFIDReader.GetInstance().CurrentUid;    // Get the uid of the badge that was scanned
                    name = LCDTextFields.Content;
                    ListOfCards.GetInstance().AddCardToList(name, uid);
                    SDCard.GetInstance().SaveCards(ListOfCards.GetInstance().CardsList);
                    _addCardState = ADD_CARD_STATE.successMSG;
                }
                catch (Exception e)
                {
                    _addCardState = ADD_CARD_STATE.errorMSG;
                }
                break;

            case ADD_CARD_STATE.errorMSG:
                DisplayError();
                Thread.Sleep(2000);
                RestoreInitialState();
                break;

            case ADD_CARD_STATE.successMSG:
                DisplaySave();
                LCD.GetInstance().DisplayText(GT.Color.Green, "Le badge a bien ete ajoute", 10, LCD.GetInstance().LcdHeight / 2);
                Thread.Sleep(2000);
                RestoreInitialState();
                break;

            default:
                _addCardState = ADD_CARD_STATE.waitRFID;
                break;
            }
        }
        /// <summary>
        /// When no menu is selected
        /// </summary>
        private void InitialState()
        {
            switch (_scanCardState)
            {
            case SCAN_CARD_STATE.waitRFID:
                if (RFIDReader.GetInstance().IsBadgeScan)
                {
                    _scanCardState = SCAN_CARD_STATE.RFIDDetected;
                }
                break;

            case SCAN_CARD_STATE.RFIDDetected:
                if (_servoState == SERVO_STATE.close)     // If the servo is lock
                {
                    bool isValid = ListOfCards.GetInstance().FindCardInlist(RFIDReader.GetInstance().CurrentUid);
                    if (isValid)
                    {
                        _scanCardState = SCAN_CARD_STATE.RFIDValid;
                    }
                    else
                    {
                        _scanCardState = SCAN_CARD_STATE.RFIDInvalid;
                    }
                }
                else
                {
                    _scanCardState = SCAN_CARD_STATE.RFIDInvalid;
                }
                break;

            case SCAN_CARD_STATE.RFIDValid:
                _servoState    = SERVO_STATE.open;
                _scanCardState = SCAN_CARD_STATE.waitRFID;
                DeleteCurrentBadgescan();
                break;

            case SCAN_CARD_STATE.RFIDInvalid:
                _servoState    = SERVO_STATE.close;
                _scanCardState = SCAN_CARD_STATE.waitRFID;
                DeleteCurrentBadgescan();
                break;

            default:
                _scanCardState = SCAN_CARD_STATE.waitRFID;
                break;
            }

            switch (_servoState)
            {
            case SERVO_STATE.open:
                ServoMotor.GetInstance().Unlock();
                _secuTimer.Start();
                break;

            case SERVO_STATE.close:
                ServoMotor.GetInstance().Lock();
                _secuTimer.Stop();
                break;

            default:
                _servoState = SERVO_STATE.close;
                break;
            }

            if (_joystickX.Read() > JOYSTICK_DOWN_LEFT) // If the joystick is down
            {
                _menu++;
                if (_menu > 4)
                {
                    _menu = 0;
                }
                DisplayMainMenu(_menu);                     // It is not removed from the test to prevent the lcd flashing
                Thread.Sleep(100);                          // Wait 0.1 second to prevent the menu from scrolling too fast
            }
            else if (_joystickX.Read() < JOYSTICK_UP_RIGHT) // The joystick is up
            {
                _menu--;
                if (_menu < 0)
                {
                    _menu = 4;
                }
                DisplayMainMenu(_menu); // It is not removed from the test to prevent the lcd flashing
                Thread.Sleep(100);      // Wait 0.1 second to prevent the menu from scrolling too fast
            }
        }