using MediaBrowser.Common.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Serialization;
using MediaBrowser.Server.Implementations.Reflection;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Server.Implementations.Sqlite
{
    /// 
    /// Class SQLiteItemRepository
    /// 
    public class SQLiteItemRepository : SqliteRepository, IItemRepository
    {
        /// 
        /// The _type mapper
        /// 
        private readonly TypeMapper _typeMapper = new TypeMapper();
        /// 
        /// The repository name
        /// 
        public const string RepositoryName = "SQLite";
        /// 
        /// Gets the name of the repository
        /// 
        /// The name.
        public string Name
        {
            get
            {
                return RepositoryName;
            }
        }
        /// 
        /// Gets the json serializer.
        /// 
        /// The json serializer.
        private readonly IJsonSerializer _jsonSerializer;
        /// 
        /// The _app paths
        /// 
        private readonly IApplicationPaths _appPaths;
        /// 
        /// Initializes a new instance of the  class.
        /// 
        /// The app paths.
        /// The json serializer.
        /// The logger.
        /// appPaths
        public SQLiteItemRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogger logger)
            : base(logger)
        {
            if (appPaths == null)
            {
                throw new ArgumentNullException("appPaths");
            }
            if (jsonSerializer == null)
            {
                throw new ArgumentNullException("jsonSerializer");
            }
            _appPaths = appPaths;
            _jsonSerializer = jsonSerializer;
        }
        /// 
        /// Opens the connection to the database
        /// 
        /// Task.
        public async Task Initialize()
        {
            var dbFile = Path.Combine(_appPaths.DataPath, "library.db");
            await ConnectToDB(dbFile).ConfigureAwait(false);
            string[] queries = {
                                "create table if not exists items (guid GUID primary key, obj_type, data BLOB)",
                                "create index if not exists idx_items on items(guid)",
                                "create table if not exists children (guid GUID, child GUID)", 
                                "create unique index if not exists idx_children on children(guid, child)",
                                "create table if not exists schema_version (table_name primary key, version)",
                                //triggers
                                TriggerSql,
                                //pragmas
                                "pragma temp_store = memory"
                               };
            RunQueries(queries);
        }
        //cascade delete triggers
        /// 
        /// The trigger SQL
        /// 
        protected string TriggerSql =
            @"CREATE TRIGGER if not exists delete_item
                AFTER DELETE
                ON items
                FOR EACH ROW
                BEGIN
                    DELETE FROM children WHERE children.guid = old.child;
                    DELETE FROM children WHERE children.child = old.child;
                END";
        /// 
        /// Save a standard item in the repo
        /// 
        /// The item.
        /// The cancellation token.
        /// Task.
        /// item
        public Task SaveItem(BaseItem item, CancellationToken cancellationToken)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            if (cancellationToken == null)
            {
                throw new ArgumentNullException("cancellationToken");
            }
            cancellationToken.ThrowIfCancellationRequested();
            return Task.Run(() =>
            {
                var serialized = _jsonSerializer.SerializeToBytes(item);
                cancellationToken.ThrowIfCancellationRequested();
                var cmd = connection.CreateCommand();
                cmd.CommandText = "replace into items (guid, obj_type, data) values (@1, @2, @3)";
                cmd.AddParam("@1", item.Id);
                cmd.AddParam("@2", item.GetType().FullName);
                cmd.AddParam("@3", serialized);
                QueueCommand(cmd);
            });
        }
        /// 
        /// Retrieve a standard item from the repo
        /// 
        /// The id.
        /// BaseItem.
        /// 
        public BaseItem RetrieveItem(Guid id)
        {
            if (id == Guid.Empty)
            {
                throw new ArgumentException();
            }
            return RetrieveItemInternal(id);
        }
        /// 
        /// Internal retrieve from items or users table
        /// 
        /// The id.
        /// BaseItem.
        /// 
        protected BaseItem RetrieveItemInternal(Guid id)
        {
            if (id == Guid.Empty)
            {
                throw new ArgumentException();
            }
            var cmd = connection.CreateCommand();
            cmd.CommandText = "select obj_type,data from items where guid = @guid";
            var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
            guidParam.Value = id;
            using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
            {
                if (reader.Read())
                {
                    var type = reader.GetString(0);
                    using (var stream = GetStream(reader, 1))
                    {
                        var itemType = _typeMapper.GetType(type);
                        if (itemType == null)
                        {
                            Logger.Error("Cannot find type {0}.  Probably belongs to plug-in that is no longer loaded.", type);
                            return null;
                        }
                        var item = _jsonSerializer.DeserializeFromStream(stream, itemType);
                        return item as BaseItem;
                    }
                }
            }
            return null;
        }
        /// 
        /// Retrieve all the children of the given folder
        /// 
        /// The parent.
        /// IEnumerable{BaseItem}.
        /// 
        public IEnumerable RetrieveChildren(Folder parent)
        {
            if (parent == null)
            {
                throw new ArgumentNullException();
            }
            var cmd = connection.CreateCommand();
            cmd.CommandText = "select obj_type,data from items where guid in (select child from children where guid = @guid)";
            var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
            guidParam.Value = parent.Id;
            using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
            {
                while (reader.Read())
                {
                    var type = reader.GetString(0);
                    using (var stream = GetStream(reader, 1))
                    {
                        var itemType = _typeMapper.GetType(type);
                        if (itemType == null)
                        {
                            Logger.Error("Cannot find type {0}.  Probably belongs to plug-in that is no longer loaded.", type);
                            continue;
                        }
                        var item = _jsonSerializer.DeserializeFromStream(stream, itemType) as BaseItem;
                        if (item != null)
                        {
                            item.Parent = parent;
                            yield return item;
                        }
                    }
                }
            }
        }
        /// 
        /// Save references to all the children for the given folder
        /// (Doesn't actually save the child entities)
        /// 
        /// The id.
        /// The children.
        /// The cancellation token.
        /// Task.
        /// id
        public Task SaveChildren(Guid id, IEnumerable children, CancellationToken cancellationToken)
        {
            if (id == Guid.Empty)
            {
                throw new ArgumentNullException("id");
            }
            if (children == null)
            {
                throw new ArgumentNullException("children");
            }
            if (cancellationToken == null)
            {
                throw new ArgumentNullException("cancellationToken");
            }
            cancellationToken.ThrowIfCancellationRequested();
            return Task.Run(() =>
            {
                var cmd = connection.CreateCommand();
                cmd.CommandText = "delete from children where guid = @guid";
                cmd.AddParam("@guid", id);
                QueueCommand(cmd);
                foreach (var child in children)
                {
                    var guid = child.Id;
                    cmd = connection.CreateCommand();
                    cmd.AddParam("@guid", id);
                    cmd.CommandText = "replace into children (guid, child) values (@guid, @child)";
                    var childParam = cmd.Parameters.Add("@child", DbType.Guid);
                    childParam.Value = guid;
                    QueueCommand(cmd);
                }
            });
        }
    }
}