using System;
using System.Configuration;
using System.Data;
using System.Linq;
using FirebirdSql.Data.FirebirdClient;
using log4net;
using Rainbow.Models;
using Rainbow.Tools;

namespace Rainbow.Data.Synchronization
{
    public static class Handler
    {
        public static void SyncCustomers(out int numInserted, out int numUpdated)
        {
            numInserted = 0;
            numUpdated = 0;
            using (var uow = new UnitOfWork())
            {
                using (var cn = new FbConnection(ConfigurationManager.ConnectionStrings["minifakturaConnection"].ConnectionString))
                {
                    cn.Open();
                    FbCommand cmd = cn.CreateCommand();
                    cmd.CommandText = "SELECT * FROM BAS_CUSTOMERS WHERE CUSTCATEGORY IS NOT NULL ORDER BY ID";
                    IDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        if ((reader["CUSTNO"] == DBNull.Value ? 0 : Convert.ToInt32(reader["CUSTNO"])) > 0)
                        {
                            string number = reader["CUSTNO"].ToString();
                            string companyName = (reader["NAME1"] + " " + reader["NAME2"]).Trim();
                            string street = reader["STREET"].ToString();
                            string country = reader["COUNTRY"].ToString();
                            string zip = reader["ZIPCODE"].ToString();
                            string city = reader["CITY"].ToString();
                            string phone = reader["PHONE1"].ToString();
                            string fax = reader["FAX"].ToString();
                            string email = reader["EMAIL"].ToString();
                            bool isReseller = Convert.ToInt32(reader["CUSTCATEGORY"]) == 1;

                            if (uow.Customers.List().Count(c => c.Number == number) == 0)
                            {
                                // insert
                                Logger.Info("Inserting customer " + number);
                                var c = new Customer
                                {
                                    Number = number,
                                    Type = isReseller ? CustomerType.Reseller : CustomerType.EndCustomer,
                                    CompanyName = companyName,
                                    DirectoryName = companyName.MakeValidFileNameName(),
                                    StreetAddress = street,
                                    Zip = zip,
                                    City = city,
                                    Country = country,
                                    Phone = phone,
                                    Fax = fax,
                                    Email = email
                                };
                                uow.Customers.Add(c);
                                numInserted++;
                            }
                            else
                            {
                                // update
                                Logger.Info("Updating customer " + number);
                                var c = uow.Customers.GetByNumber(number);
                                if (c != null)
                                {
                                    c.Type = isReseller ? CustomerType.Reseller : CustomerType.EndCustomer;
                                    c.CompanyName = companyName;
                                    c.StreetAddress = street;
                                    c.Zip = zip;
                                    c.City = city;
                                    c.Country = country;
                                    c.Phone = phone;
                                    c.Fax = fax;
                                    c.Email = email;
                                }
                                numUpdated++;
                            }
                            uow.SaveChanges();
                        }
                    }
                }
            }
        }

        private static readonly ILog Logger = LogManager.GetLogger(typeof(Handler));
    }
}
