namespace Kit.Helpers.Repository
{
    public class SQLiteFileVersionInfo
    {
        public SQLiteFileVersionInfo()
        {
            Type = string.Empty;
            Version = 0;
        }

        public string Type { get; set; }
        public long Version { get; set; }
    }

    public interface ISQLiteVersionRepository
    {
        IEnumerable<SQLiteFileVersionInfo> Select(FileContentSqlite fileContentSqlite);
        void Set(FileContentSqlite fileContentSqlite, SQLiteFileVersionInfo info);
    }

    public class SQLiteVersionRepository : ISQLiteVersionRepository
    {
        public SQLiteVersionRepository() { }

        private const string _createIfNotExists = "create table if not exists file_version (type text not null primary key, version integer not null); ";
        private const string _select = "select type, version from file_version; ";
        private const string _setByType = "delete from file_version where type = :type; insert into file_version (type, version) values (:type, :version); ";

        public IEnumerable<SQLiteFileVersionInfo> Select(FileContentSqlite fileContentSqlite)
        {
            return fileContentSqlite.ConnectionString.PrepareExecute<SQLiteFileVersionInfo>(_createIfNotExists + _select)
                .AsSqlText()
                .WithStrictSyntax()
                .AddConverter((record, list) => list.Add(new SQLiteFileVersionInfo
                {
                    Type = record.Get<string>("type"),
                    Version = record.Get<long>("version"),
                }))
                .ExecuteSelectMany();
        }

        public void Set(FileContentSqlite fileContentSqlite, SQLiteFileVersionInfo info)
        {
            fileContentSqlite.ConnectionString.PrepareExecute(_createIfNotExists + _setByType)
                .AsSqlText()
                .WithStrictSyntax()
                .AddParameter("type", info.Type)
                .AddParameter("version", info.Version)
                .ExecuteNonQuery();
        }
    }
}