using System;
using System.Data.SqlClient;

namespace SinoChemFC2PosProxy.Communicator
{
    class InitSiteCommunicator : ICommunicator
    {
        static NLog.Logger debugLogger = NLog.LogManager.LoadConfiguration("nlog.config").GetLogger("PumpHandler");

        //private readonly DebugLogger debugLogger =
        //       new DebugLogger(new IdentifiableEntity(0, "FC2PosProxyMain", "", null));
        public bool IsStarted
        {
            get { throw new NotImplementedException(); }
        }

        public bool Start()
        {
            foreach (var siteLevelNozzleId in SiteConfigUtility.Default.GetAllSiteLevelNozzleIds())
            {
                using (
                    var posSqlConnection =
                        new SqlConnection(
                            SinochemInternetPlusApp.App.PosDatabaseConnString))
                {
                    try
                    {
                        var gradeFriendlyName = Translator.GetFriendlyGradeName(SiteConfigUtility.Default.GetGradeName(siteLevelNozzleId));
                        var totalizer = SiteConfigUtility.Default.GetTotalizer(siteLevelNozzleId);
                        var setPumpOnStartingCommand =
                            new SqlCommand(string.Format("if not exists(select * from jy_info where jihao={0})" +
                                                         "	BEGIN" +
                                                         "    	insert jy_info (jihao, [status], youpin, qty, amount, fzqty, fzamount) values({0}, '{1}', N'{2}', 0, 0, '{3}', {4})" +
                                                         "	END", siteLevelNozzleId, 'F', gradeFriendlyName,
                                totalizer.Item1, totalizer.Item2), posSqlConnection);
                        debugLogger.Debug("initTable_jy_info_Command: " + setPumpOnStartingCommand.CommandText);
                        posSqlConnection.Open();
                        setPumpOnStartingCommand.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        debugLogger.Error("executing initTable_jy_info_Command failed for siteLevelNozzleId: " + siteLevelNozzleId + ", exception detail: " + ex);
                        throw;
                    }
                }
            }

            return true;
        }
    }
}