﻿// Copyright (c) 2018 Nikolay Zahariev <zahasoft.com>. Licensed under the MIT License.

namespace Zahasoft.Softuni
{
    using System;
    using System.Linq;

    public static class FourDigitsNumber
    {
        public static int[] ParseNumber()
        {
            int[] digits = new int[4];

            for (int i = 0; i < digits.Length; i++)
            {
                digits[i] = (int)char.GetNumericValue(Console.ReadKey().KeyChar);

                if (i == 0 && digits[0] == 0)
                {
                    throw new Exception("The first digit cannot be 0");
                }
            }

            return digits;
        }

        public static int SumOfDigits(int[] digits) => digits.Sum();

        public static int ReverseDigitsOreder(int[] digits)
        {
            int[] reversed = new int[4];

            int count = 0;

            for (int i = digits.Length - 1; i >= 0; i--)
            {
                reversed[count++] = digits[i];
            }

            return ConvertArrayOfDigitsToInteger(reversed);
        }

        public static int PutTheLastDigitInTheFirsPosition(int[] digits)
        {
            int[] result = new int[4];
            result[0] = digits[3];
            result[1] = digits[0];
            result[2] = digits[1];
            result[3] = digits[2];
            return ConvertArrayOfDigitsToInteger(result);
        }

        public static int ExchangeSecondAndThirdDigit(int[] digits)
        {
            int[] result = digits;
            result[1] ^= result[2];
            result[2] ^= result[1];
            result[1] ^= result[2];
            return ConvertArrayOfDigitsToInteger(result);
        }

        static int ConvertArrayOfDigitsToInteger(int[] digits) => digits[0] * 1000 + digits[1] * 100 + digits[2] * 10 + digits[3];
    }
}
