// Created with MonoDevelop
//
//    Copyright (C) 2009 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.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Text;


namespace Hiperscan.Spectroscopy.IO
{

    public static partial class CSV
    {
        private static byte[] CreateChecksum(Spectrum spectrum, byte[] salt)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                CSV.Write(spectrum, ms, CSV.DEFAULT_CULTURE);
                using (HMACSHA384 sha = new HMACSHA384(salt))
                {
                    return sha.ComputeHash(ms.ToArray());
                }
            }
        }

        private static byte[] CreateChecksum(Stream stream, byte[] salt)
        {
            using (StreamReader reader = new StreamReader(stream))
            using (MemoryStream ms = new MemoryStream())
            {
                stream.Position = 0;
                using (StreamWriter writer = new StreamWriter(ms))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (line.StartsWith("# " + Parser.Checksum, StringComparison.InvariantCulture))
                            continue;
                        writer.WriteLine(line);
                    }
                }

                using (HMACSHA384 sha = new HMACSHA384(salt))
                {
                    return sha.ComputeHash(ms.ToArray());
                }
            }
        }

        private static string GetStringFromHash(byte[] hash)
        {
            StringBuilder sb = new StringBuilder();

            foreach (byte b in hash)
            {
                sb.Append(b.ToString("X2"));
            }

            return sb.ToString();
        }

        private static byte[] GetHashFromString(string s)
        {
            List<byte> hash = new List<byte>();

            for (int ix = 0; ix < s.Length; ix += 2)
            {
                hash.Add(byte.Parse(s.Substring(ix, 2), NumberStyles.HexNumber));
            }

            return hash.ToArray();
        }
    }
}