using System.ComponentModel;
using System.Web.Services;

using BeWo.Data;
using BeWo.Data.Access;
using BeWo.Service.ServiceContracts;
using BeWo.Service.ServiceImplementations;
using BeWoPlanerMobil.Service;
using BS.Shared;
using BS.Shared.Core;
using Newtonsoft.Json;
using ASPHibernateSessionManager = BeWoPlanerMobil.Service.ASPHibernateSessionManager;

namespace BeWoPlanerMobil
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // Wenn der Aufruf dieses Webdiensts aus einem Skript mithilfe von ASP.NET AJAX zulässig sein soll, heben Sie die Kommentarmarkierung für die folgende Zeile auf. 
    // [System.Web.Script.Services.ScriptService]
    public class TestWebService : WebService
    {
        protected readonly ICustomerService CustomerService = new MobileSessionFacade().CustomerService;
        protected readonly IUserService     UserService     = new MobileSessionFacade().UserService;
        protected readonly IEmployeeService EmployeeService = new MobileSessionFacade().EmployeeService;

        [WebMethod(EnableSession = true)]
        public void TestLogin(string pUserName, string pPassword)
        {
            MobileSessionFacade.Tenant = "demo";
            SessionFacade.Tenant       = "demo";

            ASPHibernateSessionManager.ConfigureHibernateSessionForWebService();

            var s = new UserServiceImp();

            if (s.IsUserValid(pUserName, pPassword, null, "MobilClient", false) == UserValidationResult.UserValid)
            {
                var user = DAOFactory.UserDAO.FindUserByLoginName(pUserName);

                if(user == null || !DAOFactory.UserDAO.CheckPassword(user, pPassword))
                {
                    return;
                }

                MobileSessionFacade.LoggedInUser = user;
            }
        }

        [WebMethod(EnableSession = true)]
        public string TestFunktion(long pCustomerOid)
        {
            MobileSessionFacade.Tenant = "demo";

            ASPHibernateSessionManager.ConfigureHibernateSessionForWebService();

            var result = CustomerService.GetCompactCustomerDC(pCustomerOid);

            return SerializeObject(result);
        }

        private static string SerializeObject(object obj)
        {
            return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new ShouldSerializeContractResolver(), ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
        }
    }
}
