//-----------------------------------------------------------------------
// 
//     Copyright (c) Microsoft Corporation.
// 
//-----------------------------------------------------------------------
namespace Microsoft.Isam.Esent.Interop
{
    using System.Text;
    using Microsoft.Isam.Esent.Interop.Implementation;
    /// 
    /// Enumerate the names of tables in a database.
    /// 
    internal sealed class TableNameEnumerator : TableEnumerator
    {
        /// 
        /// The database containing the tables.
        /// 
        private readonly JET_DBID dbid;
        /// 
        /// Object list containing information about tables.
        /// 
        private JET_OBJECTLIST objectlist;
        /// 
        /// Initializes a new instance of the  class.
        /// 
        /// 
        /// The session to use.
        /// 
        /// 
        /// The database to get the table names from.
        /// 
        public TableNameEnumerator(JET_SESID sesid, JET_DBID dbid) : base(sesid)
        {
            this.dbid = dbid;
        }
        /// 
        /// Open the table to be enumerated. This should set .
        /// 
        protected override void OpenTable()
        {
            Api.JetGetObjectInfo(this.Sesid, this.dbid, out this.objectlist);
            this.TableidToEnumerate = this.objectlist.tableid;
        }
        /// 
        /// Determine if the current entry in the table being enumerated should
        /// be skipped (not returned). Here we are skipping system tables.
        /// 
        /// True if the current entry should be skipped.
        protected override bool SkipCurrent()
        {
            int flags = (int)Api.RetrieveColumnAsInt32(this.Sesid, this.TableidToEnumerate, this.objectlist.columnidflags);
            return ObjectInfoFlags.System == ((ObjectInfoFlags)flags & ObjectInfoFlags.System);
        }
        /// 
        /// Gets the entry the cursor is currently positioned on.
        /// 
        /// The entry the cursor is currently positioned on.
        protected override string GetCurrent()
        {
            // If we use the wide API (Vista+), then the temp table will be in UTF-16.
            Encoding encodingOfTextColumns = EsentVersion.SupportsVistaFeatures ? Encoding.Unicode : LibraryHelpers.EncodingASCII;
            string name = Api.RetrieveColumnAsString(
                this.Sesid,
                this.TableidToEnumerate,
                this.objectlist.columnidobjectname,
                encodingOfTextColumns,
                RetrieveColumnGrbit.None);
            return StringCache.TryToIntern(name);
        }
    }
}