using System;
using System.Data;
using System.Collections;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using digioz;
using Eloquera.Client;
namespace digioz
{
    public class Eloquera : IDataNonRelational
    {
        public PortalSettings coPortalSettings;
        private DB db = null;        
        public Eloquera(PortalSettings poPortalSettings)
        {
            coPortalSettings = poPortalSettings;
        }

        public void openEntity()
        {
            if (db == null)
            {
                string cnString = coPortalSettings.ConnectionString;
                if (cnString == String.Empty)
                {
                    cnString = "Server=" + coPortalSettings.DBHost + ";";
                    if (coPortalSettings.DBUser != String.Empty)
                       cnString += "user=" + coPortalSettings.DBUser + ";";
                    
                    cnString += "password=" + coPortalSettings.DBPass + ";options=none";                    
                }
                db = new DB(cnString);
                if (Array.IndexOf(db.GetDbList(), coPortalSettings.DBName) < 0)
                    db.CreateDatabase(coPortalSettings.DBName);
                db.OpenDatabase(coPortalSettings.DBName);
            }
        }
        public void closeEntity()
        {
            if (db != null)
                db.Close();
            db = null;
        }
        public object GetEntity(int piID)
        {
            throw new ApplicationException("Method not Implemented.");
        }
        public object GetEntity(string psEntityName, int piID)
        {
            if (db != null)
                return db.ExecuteScalar("SELECT " + psEntityName + " WHERE ID = " + piID);
            else
                return null;
        }
        public IEnumerable GetEntity(string psEntityName)
        {
            if (db != null)
                return db.ExecuteQuery("SELECT " + psEntityName);
            else
                return null;
        }

        public bool SaveEntity(object poObject)
        {
            if (db != null)
            {
                if (db.Store(poObject) > 0)
                    return true;
            }

            return false;
        }

        public bool DeleteEntity(object poObject)
        {
            return false;
        }

        public bool DeleteEntity(string psEntityName, int piID)
        {
            if (db != null)
            {
                db.DeleteAll(GetEntity(psEntityName, piID));
                return true;
            }
            else
                return false;
        }

        public bool CreateEntity(object poObject)
        {
            return SaveEntity(poObject);
        }
    }
}
