// Created with MonoDevelop
//
//    QuickStep: Acquire, view and identify spectra 
//    Copyright (C) 2017 Thomas Klose & Torsten Schache, Hiperscan GmbH Dresden, Germany
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.



using System;
using System.Text;
using System.IO;
using System.Security.Cryptography;
      
using Hiperscan.Unix;
using System.Runtime.Serialization;

namespace Hiperscan.ApoIdentCommon               
{
    public static class Base64AddressData
	{
        private const string SECRET = "xF3Afc8izaLUWrSw7cSKquhUEvAX";

		public static string Encode(string[] entries)
		{
			StringBuilder data = new StringBuilder();

			foreach (string entry in entries)
			{
				if (entry.Contains("\n"))
					throw new ArgumentException(Catalog.GetString("Cannot encode entries which contain newlines."));

				data.AppendLine(entry);
			}

			string hash_code = Base64AddressData.Sha256(data + SECRET);
			byte[] buf = Encoding.UTF8.GetBytes(data.ToString() + hash_code);

			return Convert.ToBase64String(buf, Base64FormattingOptions.InsertLineBreaks);
		}

        public static DecodedBase64Address Decode(string base64_data)
		{
			byte[] buf = Convert.FromBase64String(base64_data);

			string data = Encoding.UTF8.GetString(buf);
			int ix = data.LastIndexOf('\n');

			string saved_hash = data.Substring(ix+1);
			data = data.Substring(0, ix);

			string hash_code = Base64AddressData.Sha256(data + "\n" + SECRET);

			if (saved_hash != hash_code)
				throw new InvalidDataException(Catalog.GetString("Cannot decode data. The consistency check failed."));

            return new DecodedBase64Address(data.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None));
		}

		private static string Sha256(string s)
		{
			SHA256Managed sha256 = new SHA256Managed();
			StringBuilder hash = new StringBuilder();

			byte[] buf = sha256.ComputeHash(Encoding.UTF8.GetBytes(s), 0, Encoding.UTF8.GetByteCount(s));

			foreach (byte b in buf)
			{
				hash.Append(b.ToString("x2"));
			}
			return hash.ToString();
		}
	}
}
