Ejemplo n.º 1
0
        /// <summary>
        /// <inheritdoc/>
        /// <remarks>
        /// This is the appropriate action for <see cref="T:VendingMachine.WaitUserSelectionState"/> i.e. when the machine is ready for the user to select an item.
        /// <list type="bullet">
        /// <item>
        ///     <description>
        ///     Case 1. Checks the total machine inventory and if it is empty, it transitions back to <see cref="T:VendingMachine.SoldOutState"/>.
        ///     Machine needs a refill.
        ///     </description>
        /// </item>
        /// <item>
        ///     <description>
        ///     Case 2. Checks if there is sufficient stock of the selected item and transitions the state to <see cref="T:VendingMachine.WaitCoinState"/>.
        ///     User is in a position to insert the coins.
        ///     </description>
        /// </item>
        /// <item>
        ///     <description>
        ///     Case 3. If there is no stock left for the selected item it transitions back to <see cref="T:VendingMachine.WaitUserSelectionState"/>.
        ///     This allows the user to reselect a different item.
        ///     </description>
        /// </item>
        /// </list>
        /// </remarks>
        /// </summary>
        /// <param name="itemName">Name of the product</param>
        public void SelectItem(string itemName)
        {
            // Machine's inventory is Zero. Everything is sold out. Make the state transition to the sold out state
            if (_machine.TotalItemCount == 0)
            {
                _machine.State = _machine.GetSoldOutState;
                return;
            }

            // check if the machine has enough stock of the selected item
            if (_machine.GetItemCount(itemName) > 0)
            {
                // tell the machine to update the selected product in transaction
                _machine.AddItem(itemName);
                _machine.DisplayMessage(string.Format("You selected {0} with a value of {1} ", _machine.SelectedItem.Name, _machine.SelectedItem.Price));

                // change the state to "wait for coins".
                _machine.State = _machine.GetWaitCoinState;

                // display an appropriate message to the user
                _machine.DisplayMessage(string.Format("Please insert coins to buy '{0}'", _machine.SelectedItem.Name));
            }
            else
            {
                // Sufficient stock is not available. Hence, change the state to wait selection state
                // such that the user can select a different drink. Notify this to the user.
                _machine.State = _machine.GetUserSelectItemState;
                throw new ApplicationException(string.Format("Sorry, '{0}' is not available. Please select a different drink.",
                                                             _machine.SelectedItem.Name));
            }
        }