using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _7_Roman {
	internal static class RomanConverter {
		static Dictionary<string, int> RomanToInt;
		static Dictionary<int, string> IntToRoman;


		static RomanConverter() {
			RomanToInt = new Dictionary<string, int>(StringComparer.InvariantCultureIgnoreCase) {
				{ "I", 1 },
				{ "V", 5 },
				{ "X", 10 },
				{ "L", 50 },
				{ "C", 100 },
				{ "D", 500 },
				{ "M", 1000 },
			};

			IntToRoman = RomanToInt.ToDictionary(x => x.Value, x => x.Key);
		}

		static List<int> StringToIntList(string str) {
			var ret = new List<int>();

			foreach (var c in str) {
				var toS = c.ToString();
				if (RomanToInt.TryGetValue(toS, out var val)) {
					ret.Add(val);
				} else
					throw new FormatException($"Character {toS} is not a valid Roman numeral.");
			}

			return ret;
		}

		public static int ConvertRomanToInt(string roman) {
			var ret = 0;

			var intList = StringToIntList(roman);

			var i = 0;
			while (i < intList.Count) {
				var next = i + 1;
				if (next == intList.Count) {
					ret += intList[i];
				} else {
					if (intList[i] < intList[next])
						ret -= intList[i];
					else
						ret += intList[i];
				}

				i++;
			}

			return ret;
		}
	}
}
