using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Collections.Generic;

namespace digioz
{
    public class PageHitsManagement
    {
        private static PortalSettings coPortalSettings;
        
        public PageHitsManagement()
        {}

        public static Dictionary<string, int> GetHitStatistics()
        {
            coPortalSettings = PortalSettingsManagement.GetPortalSettings();
            Dictionary<string, int> result = new Dictionary<string, int>();

            if (coPortalSettings.DBRelational == true)
            {
                IDataRelational loDB = DataFactory.GetDataObject(coPortalSettings);
                string lsSQL = String.Empty;
                int liCount;
                DbParameter[] loParameters = new DbParameter[0];
                lsSQL = "spGetPageHits";

                try
                {
                    loDB.openConnection();
                    DataTable table = loDB.QueryDBDatasetProc(lsSQL, out liCount, loParameters);

                    foreach (DataRow row in table.Rows)
                    {
                        result.Add(row[0].ToString(), (int)row[1]);
                    }
                }
                finally
                {
                    loDB.closeConnection();
                }
            }

            return result;
        }

        public static bool IncreaseHitCount(string pageName)
        {
            coPortalSettings = PortalSettingsManagement.GetPortalSettings();
            bool isSuccess = false;

            if (coPortalSettings.DBRelational == true)
            {
                IDataRelational loDB = DataFactory.GetDataObject(coPortalSettings);
                string lsSQL = String.Empty;
                int liCount = 0;
                DbParameter[] loParameters;

                loParameters = new DbParameter[1];
                loParameters[0] = new SqlParameter("@page_name", SqlDbType.VarChar);
                loParameters[0].Value = pageName;
                lsSQL = "spUpdatePageHits";

                try
                {
                    loDB.openConnection();
                    loDB.ExecDBProc(lsSQL, out liCount, loParameters);
                    isSuccess = true;
                }
                finally
                {
                    loDB.closeConnection();
                }
            }

            return isSuccess;
        }
    }
}