using System.Collections.Generic;

namespace DapperExtensions.Sql
{
    /// <summary>
    /// Postgre语句配置扩展类
    /// </summary>
    public class PostgreSqlDialect : SqlDialectBase
    {
        /// <summary>
        /// 获取自增Sql
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public override string GetIdentitySql(string tableName)
        {
            return "SELECT LASTVAL() AS Id";
        }

        /// <summary>
        /// 获取分页Sql
        /// </summary>
        /// <param name="sql">SQL命令</param>
        /// <param name="page">页码</param>
        /// <param name="resultsPerPage">页大小</param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public override string GetPagingSql(string sql, int page, int resultsPerPage, IDictionary<string, object> parameters)
        {
            int startValue = page * resultsPerPage;
            return GetSetSql(sql, startValue, resultsPerPage, parameters);
        }

        /// <summary>
        /// 获取分页SQL
        /// </summary>
        /// <param name="sql">SQL命令</param>
        /// <param name="firstResult">开始值</param>
        /// <param name="maxResults">最大值/结束值</param>
        /// <param name="parameters">参数</param>
        /// <returns></returns>
        public override string GetSetSql(string sql, int firstResult, int maxResults, IDictionary<string, object> parameters)
        {
            string result = string.Format("{0} LIMIT @firstResult OFFSET @pageStartRowNbr", sql);
            parameters.Add("@firstResult", firstResult);
            parameters.Add("@maxResults", maxResults);
            return result;
        }

        /// <summary>
        /// 获取列名
        /// </summary>
        /// <param name="prefix">前缀[比如:a.Name]</param>
        /// <param name="columnName">列名</param>
        /// <param name="alias">别名</param>
        /// <returns></returns>
        public override string GetColumnName(string prefix, string columnName, string alias)
        {
            return base.GetColumnName(null, columnName, alias).ToLower();
        }

        /// <summary>
        /// 获取表名
        /// </summary>
        /// <param name="schemaName">架构名称</param>
        /// <param name="tableName">表名</param>
        /// <param name="alias">别名</param>
        /// <param name="dbName">数据库名称</param>
        /// <returns></returns>
        public override string GetTableName(string schemaName, string tableName, string alias, string dbName = "")
        {
            return base.GetTableName(schemaName, tableName, alias).ToLower();
        }
    }
}