using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using ServiceData.Complex;
namespace ServiceWeb.AjaxWCFServices
{
    [ServiceContract]
    //[ServiceKnownType(typeof(BusinessEntity))]
    //[ServiceKnownType(typeof(CustomerEntity))]
    //[ServiceKnownType(typeof(VendorEntity))]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class ComplexService
    {

        [OperationContract]
        public VariousEntities Save2(VariousEntities variousEntities, string stringValue, VariousEntities various2, int intValue)
        {
            return Save(variousEntities);
        }
        
        [OperationContract]
        public VariousEntities Save(VariousEntities variousEntities)
        {
            //throw new InvalidOperationException("Method is not supported");

            foreach (object entity in variousEntities.Entities)
            {
                CustomerEntity customer = entity as CustomerEntity;
                if (customer != null)
                {
                    customer.ApprovalDate = DateTime.Now;
                    customer.Id = GetNextId();
                    break;
                }

                VendorEntity vendor = entity as VendorEntity;
                if (vendor != null)
                {
                    vendor.CreditRating = "A";
                    vendor.Id = GetNextId();
                    break;
                }

                BusinessEntity business = entity as BusinessEntity;
                if (business != null)
                {
                    business.Id = GetNextId();
                }
            }
            return variousEntities;
        }

        [OperationContract]
        public BusinessEntity SaveBusiness(BusinessEntity business)
        {
            if (business != null)
            {
                business.Id = GetNextId();
            }

            return business;
        }

        [OperationContract]
        public CustomerEntity SaveCustomer(CustomerEntity customer)
        {
            if (customer != null)
            {
                customer.ApprovalDate = DateTime.Now;
                customer.Id = GetNextId();
            }

            return customer;
        }

        [OperationContract]
        public VendorEntity SaveVendor(VendorEntity vendor)
        {
            if (vendor != null)
            {
                vendor.CreditRating = "A";
                vendor.Id = GetNextId();
            }

            return vendor;
        }

        int GetNextId()
        {
            Random random = new Random();
            return random.Next();
        }
    }
}
