using System;
using System.Linq;

namespace Knoks.Framework.Cryptography
{
    public class PasswordResult : IPasswordResult
    {
        public string Version { get; private set; }
        public byte[] Password { get; private set; }
        public byte[] Salt { get; private set; }

        public PasswordResult(string version, byte[] password, byte[] salt)
        {
            Version = version;
            Password = password;
            Salt = salt;
        }

        public PasswordResult(string flatString)
        {
            try
            {
                var strArr = flatString.Split('|');

                Version = strArr[0];
                Password = Convert.FromBase64String(strArr[1]);
                Salt = Convert.FromBase64String(strArr[2]);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Invalid object creation from flat string.", ex);
            }
        }

        public string ToFlatString()
        {
            return string.Format("{0}|{1}|{2}", Version, Convert.ToBase64String(Password), Convert.ToBase64String(Salt));
        }

        public bool IsIdentical(IPasswordResult other)
        {
            return string.Equals(Version, other.Version, StringComparison.OrdinalIgnoreCase) &&
                Password.SequenceEqual(other.Password) &&
                Salt.SequenceEqual(other.Salt);
        }
    }
}