Exemplo n.º 1
0
        /// <inheritdoc />
        protected override async Task <Result <DateTime, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var dateResult = await Date.Run(stateMonad, cancellationToken)
                             .Map(async x => await x.GetStringAsync());

            if (dateResult.IsFailure)
            {
                return(dateResult.ConvertFailure <DateTime>());
            }

            string?inputFormat = null;

            if (InputFormat != null)
            {
                var inputFormatResult = await InputFormat.Run(stateMonad, cancellationToken)
                                        .Map(async x => await x.GetStringAsync());

                if (inputFormatResult.IsFailure)
                {
                    return(inputFormatResult.ConvertFailure <DateTime>());
                }

                inputFormat = inputFormatResult.Value;
            }

            var cultureResult = await Culture.Run(stateMonad, cancellationToken)
                                .Map(async x => await x.GetStringAsync());

            if (cultureResult.IsFailure)
            {
                return(cultureResult.ConvertFailure <DateTime>());
            }

            CultureInfo ci;

            try
            {
                ci = new CultureInfo(cultureResult.Value);
            }
            catch (CultureNotFoundException)
            {
                return(new SingleError(
                           new ErrorLocation(this),
                           ErrorCode.CouldNotParse,
                           cultureResult.Value,
                           nameof(Culture)
                           ));
            }

            DateTime date;

            if (inputFormat == null)
            {
                try
                {
                    date = DateTime.Parse(dateResult.Value, ci);
                }
                catch (FormatException fe)
                {
                    return(new SingleError(
                               new ErrorLocation(this),
                               fe,
                               ErrorCode.CouldNotParse
                               ));
                }
            }
            else
            {
                try
                {
                    date = DateTime.ParseExact(dateResult.Value, inputFormat, ci);
                }
                catch (FormatException fe)
                {
                    return(new SingleError(
                               new ErrorLocation(this),
                               fe,
                               ErrorCode.CouldNotParse
                               ));
                }
            }

            return(date);
        }