/*
    Copyright 2011 MCForge
        
    Dual-licensed under the Educational Community License, Version 2.0 and
    the GNU General Public License, Version 3 (the "Licenses"); you may
    not use this file except in compliance with the Licenses. You may
    obtain a copy of the Licenses at
    
    http://www.opensource.org/licenses/ecl2.php
    http://www.gnu.org/licenses/gpl-3.0.html
    
    Unless required by applicable law or agreed to in writing,
    software distributed under the Licenses are distributed on an "AS IS"
    BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
    or implied. See the Licenses for the specific language governing
    permissions and limitations under the Licenses.
 */
using System;
using System.Data;
using System.IO;

namespace MCGalaxy.SQL {
    public static partial class Database {
        
        public static IDatabaseBackend Backend;
        
        public static bool TableExists(string table) {
            return Backend.TableExists(table);
        }
        
        [Obsolete("Use Execute() method instead.")]
        public static void executeQuery(string sql, bool createDB = false) {
            ParameterisedQuery query = Backend.GetStaticParameterised();
            Execute(query, sql, createDB, null);
        }
        
        public static void Execute(string sql) {
            ParameterisedQuery query = Backend.GetStaticParameterised();
            Execute(query, sql, false, null);
        }
        
        public static void Execute(string sql, params object[] args) {
            ParameterisedQuery query = Backend.CreateParameterised();
            Execute(query, sql, false, args);
        }
        
        public static void ExecuteReader(string sql, ReaderCallback callback, params object[] args) {
            ParameterisedQuery query = Backend.CreateParameterised();
            DoDatabaseCall(query, sql, false, null, callback, args);
        }
        
        [Obsolete("Use Fill() method instead.")]
        public static DataTable fillData(string sql, bool skipError = false) {
            ParameterisedQuery query = Backend.GetStaticParameterised();
            return Fill(query, sql, null);
        }
        
        public static DataTable Fill(string sql) {
            ParameterisedQuery query = Backend.GetStaticParameterised();
            return Fill(query, sql, null);
        }
        
        public static DataTable Fill(string sql, params object[] args) {
            ParameterisedQuery query = Backend.CreateParameterised();
            return Fill(query, sql, args);
        }


        internal static void Execute(ParameterisedQuery query, string sql, bool createDB, params object[] args) {
            DoDatabaseCall(query, sql, createDB, null, null, args);
        }
        
        internal static DataTable Fill(ParameterisedQuery query, string sql, params object[] args) {
            using (DataTable results = new DataTable("toReturn")) {
                DoDatabaseCall(query, sql, false, results, null, args);
                return results;
            }
        }
        
        static void DoDatabaseCall(ParameterisedQuery query, string sql, bool createDB, 
                                   DataTable results, ReaderCallback callback, params object[] args) {
            BindParams(query, args);
            string connString = Backend.ConnectionString;
            Exception e = null;
            
            for (int i = 0; i < 10; i++) {
                try {
                    if (callback != null) {
                        query.ExecuteReader(sql, connString, callback);
                    } else if (results == null) {
                        query.Execute(sql, connString, createDB);
                    } else {
                        query.Fill(sql, connString, results);
                    }
                    
                    query.ClearParams();
                    return;
                } catch (Exception ex) {
                    e = ex; // try yet again
                }
            }
            
            File.AppendAllText("MySQL_error.log", DateTime.Now + " " + sql + "\r\n");
            Server.ErrorLog(e);
        }

        
        static readonly object idsLock = new object();
        static string[] ids = null;
        static void BindParams(ParameterisedQuery query, object[] args) {
            if (args == null || args.Length == 0) return;
            string[] names = GetParamNames(args.Length);
            for (int i = 0; i < args.Length; i++)
                query.AddParam(names[i], args[i]);
        }
        
        internal static string[] GetParamNames(int count) {
            // Avoid allocation overhead from string concat every query by caching
            string[] names = null;
            lock (idsLock) {
                names = ids;
                if (ids == null || count > ids.Length) {
                    ids = new string[count];
                    for (int i = 0; i < count; i++)
                        ids[i] = "@" + i;
                    names = ids;
                }
            }
            return names;
        }
    }
}