/*
 * Copyright 2018-2019 Chris Cromer
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

namespace LibSernatur {
	/**
	 * The person name space
	 */
	namespace Misc {

		/**
		 * The errors that can be thrown by the Rut class
		 */
		public errordomain InvalidRut {
			/**
			 * The RUT is invalid
			 */
			INVALID,
			/**
			 * The RUT is too large, larger than 100.000.000
			 */
			TOOLARGE,
			/**
			 * The verifier is incorrect
			 */
			INVALIDVERIFIER
		}

		public class Money : GLib.Object {
			public static string format_int (uint value) {
				string money = "";
				string temp_money = value.to_string ().reverse ();
				int money_length = temp_money.length;
				for (int i = 0; i < money_length; i++) {
					money = money + temp_money.get_char(i).to_string ();
					if ((i + 1) % 3 == 0) {
						if (i != money_length - 1) {
							money = money + ".";
						}
					}
				}
				money = money.reverse ();
				return "$" + money;
			}

			public static string format_uint (uint value) {
				string money = "";
				string temp_money = value.to_string ().reverse ();
				int money_length = temp_money.length;
				for (int i = 0; i < money_length; i++) {
					money = money + temp_money.get_char(i).to_string ();
					if ((i + 1) % 3 == 0) {
						if (i != money_length - 1) {
							money = money + ".";
						}
					}
				}
				money = money.reverse ();
				return "$" + money;
			}

			public static string format_string (string value) {
				string money = "";
				string temp_money = value.reverse ();
				int money_length = temp_money.length;
				for (int i = 0; i < money_length; i++) {
					money = money + temp_money.get_char(i).to_string ();
					if ((i + 1) % 3 == 0) {
						if (i != money_length - 1) {
							money = money + ".";
						}
					}
				}
				money = money.reverse ();
				return "$" + money;
			}
		}

		/**
		 * This class handles parsing and validation of RUTs
		 */
		public class Rut : GLib.Object {
			/**
			 * The cleaned RUT
			 */
			private string clean_rut;
			/**
			 * The pretty RUT, e.g. with periods and dash
			 */
			private string pretty_rut;
			/**
			 * The verifier
			 */
			private unichar verifier;

			/**
			 * The type of identifier
			 */
			public enum Type {
				/**
				 * Company
				 */
				RUN,
				/**
				 * Person
				 */
				RUT
			}

			/**
			 * Initialize the Rut class
			 * @param rut The RUT to parse
			 * @throws InvalidRut Thrown if the RUT is invalid in any way
			 */
			public Rut (string rut) throws InvalidRut {
				parse (rut);
			}

			/**
			 * Parse the rut that was passed to the constructor
			 * @param rut The RUT to parse
			 * @throws InvalidRut Thrown if the RUT is invalid in any way
			 */
			private void parse (string rut) throws InvalidRut {
				try {
					var regex = new Regex ("^[ ]*([0-9.]{0,11}[\\-]?[0-9kK])?[ ]*$");
					if (!regex.match (rut)) {
						throw new InvalidRut.INVALID (dgettext (null, "The RUT %s has an invalid character!"), rut);
					}
				}
				catch (Error e) {
					#if DEBUG
						error (e.message);
					#else
						warning (e.message);
					#endif
				}
				try {
					var regex = new Regex ("([.-])");
					string new_rut = rut.up ();
					new_rut = new_rut.strip ();
					rut = regex.replace (new_rut, new_rut.length, 0, "");
					if (int.parse (rut.substring (0, rut.length - 1)) > 100000000) {
						throw new InvalidRut.TOOLARGE (dgettext (null, "The RUT %s is too big!"), rut);
					}
					this.verifier = rut.get_char (rut.length - 1);
					this.clean_rut = rut.substring (0, rut.length - 1);
					if (generate_verfifier (this.clean_rut) != this.verifier) {
						throw new InvalidRut.INVALIDVERIFIER (dgettext (null, "The verifier %C is invalid!"), this.verifier);
					}
					pretty();
				}
				catch (Error e) {
					#if DEBUG
						error (e.message);
					#else
						warning (e.message);
					#endif
				}
			}

			/**
			 * Add periods and dash to the RUT to make it look pretty
			 */
			private void pretty () {
				string new_rut = "";
				string temp_rut = this.clean_rut.reverse ();
				int rut_length = this.clean_rut.length;
				for (int i = 0; i < rut_length; i++) {
					new_rut = new_rut + temp_rut.get_char(i).to_string ();
					if ((i + 1) % 3 == 0) {
						if (i != rut_length - 1) {
							new_rut = new_rut + ".";
						}
					}
				}
				new_rut = new_rut.reverse ();
				this.pretty_rut = new_rut + "-" + this.verifier.to_string ();
			}

			/**
			 * Generate a verifier based off the RUT
			 * @param rut The RUT used to generate the verifier
			 * @return Returns the verifier
			 */
			private unichar generate_verfifier (string rut) {
				/**
				 * 1. Multiply each digit of the RUT by 2, 3, ..., 7, 2, 3, ... from the end of the RUT moving forward.
				 * 2. Add the partial multiplications.
				 * 3. Calculate the remainder of the division by 11.
				 * 4. The verifier is 11 minus the previous result. If the result is 10, change it to K.
				 */
				int multiplier = 2;
				int sum = 0;
				int remainder;
				int division;
				int rut_length = rut.length;

				// Steps 1 and 2
				for (int i = rut_length - 1; i >= 0; i--) {
					sum = sum + (int.parse (rut.substring(i, 1)) * multiplier);
					multiplier++;
					if (multiplier == 8) {
						multiplier = 2;
					}
				}

				// Step 3
				division = sum / 11;
				division = division * 11;
				remainder = sum - division;

				// Step 4
				if (remainder != 0) {
					remainder = 11 - remainder;
				}

				// Let's return their verifier
				if (remainder == 10) {
					// Their verifier is 10 so let's return K.
					return 'K';
				}
				else {
					// Add the '0' to convert from int to unichar
					return (unichar) remainder + '0';
				}
			}

			/**
			 * Get the clean RUT
			 * @return Returns the cleaned up RUT
			 */
			public string get_clean_rut () {
				return this.clean_rut + this.verifier.to_string ();
			}

			/**
			 * Get the RUT
			 * @return Returns the RUT with periods and dash
			 */
			public string get_rut () {
				return this.pretty_rut;
			}

			/**
			 * Check the type of identifier
			 * @return Returns the type of identifier, Type.RUT if it's a company or Type.RUN if it's a person
			 */
			public Type type () {
				uint rut = int.parse (this.clean_rut);
				if (rut < 100000000 && rut > 50000000) {
					// Company
					return Type.RUT;
				}
				else {
					// Person
					return Type.RUN;
				}
			}
		}
	}
}
