using System;
using System.IO;

namespace InABox.Core
{

    // We removed ISkipLoad because it seemed pointless.
    [UserTracking(typeof(User))]
    public class Document : Entity, IRemotable, IPersistent, ILicense<CoreLicense>
    {
        [TextBoxEditor]
        [EditorSequence(1)]
        public string FileName { get; set; } = "";

        [CheckBoxEditor]
        [EditorSequence(2)]
        public bool Private { get; set; }

        [TimestampEditor(Editable = Editable.Hidden)]
        public DateTime TimeStamp { get; set; }

        [CodeEditor(Editable = Editable.Enabled)]
        public string CRC { get; set; } = "";

        /// <summary>
        /// This is a special property, and is not stored in the database. Hence, it <b>cannot</b> be available to <see cref="DocumentLink"/>,
        /// and neither can it be filtered on.
        /// </summary>
        [NullEditor]
        [ExternalStorage]
        public byte[] Data { get; set; } = Array.Empty<byte>();

        /*[DoNotSerialize]
        [DoNotPersist]
        [NullEditor]
        public string AsBase64
        {
            get => Data == null ? "" : Convert.ToBase64String(Data);
            set => Data = Convert.FromBase64String(value);
        }*/

        [TimestampEditor(Editable = Editable.Hidden)]
        public override DateTime Created
        {
            get => base.Created;
            set => base.Created = value;
        }

        [TextBoxEditor(Editable = Editable.Hidden)]
        public override string CreatedBy
        {
            get => base.CreatedBy;
            set => base.CreatedBy = value;
        }

        public override string ToString()
        {
            return FileName;
        }

        public static Document FromFile(string filename)
        {
            var data = File.ReadAllBytes(filename);
            return new Document
            {
                Data = data,
                FileName = Path.GetFileName(filename),
                CRC = CoreUtils.CalculateCRC(data),
                TimeStamp = new FileInfo(filename).LastWriteTime
            };
        }
    }
}