using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using Dapper;

namespace QQPlus.Faq
{
    public class DbBase : IDisposable
    {
        public static readonly object LockDb = new object();
        private IDbConnection _conn;
        private IDbTransaction _tran;
        public IDbConnection Conn
        {
            get
            {
                if (this._conn.State == ConnectionState.Closed)
                {
                    this._conn.Open();
                }
                return this._conn;
            }
        }
        public IDbTransaction Tran
        {
            get
            {
                return this._tran;
            }
        }
        public static string DataSource = null;

        public DbBase(string dataSource = null)
        {
            if (dataSource == null)
                this._conn = new SQLiteConnection(DataSource);
            else
                this._conn = new SQLiteConnection(dataSource);
            this._conn.Open();
        }

        public void BeginTransation()
        {
            if (this._tran == null)
            {
                this._tran = this._conn.BeginTransaction();
            }
        }
        private void CloseConn()
        {
            if (this._conn != null && this._conn.State == ConnectionState.Open)
            {
                if (this._tran != null)
                {
                    this._tran.Commit();
                    this._tran = null;
                }
                this._conn.Close();
                this._conn = null;
            }
        }
        public void Dispose()
        {
            this.CloseConn();
        }
        public void EndTransaction()
        {
            if (this._tran != null)
            {
                try
                {
                    this._tran.Commit();
                }
                finally
                {
                    this._tran = null;
                }
            }
        }
        public void RollBack()
        {
            if (this._tran != null)
            {
                try
                {
                    this._tran.Rollback();
                }
                finally
                {
                    this._tran = null;
                }
            }
        }
    }
}
