// POST: api/Notifications
        /*  [Route("api/v1/notifications", Name = "PostNotifications")]*/
        public async Task<IHttpActionResult> Post([FromBody]NotificationDTO notificaton)
        {


            ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;

            var parsedAccidentId = APIURLParserV1.ParseResouceURIForPrimaryKeyValue(notificaton.Accident);
            var existingObjectInDb = _db.Accidents.Include(x => x.Customer).FirstOrDefault(x => x.Id == parsedAccidentId);

            if (existingObjectInDb == null)
            {
               
GenerateBaseLog(ApiLogType.Warning,
  LogMessageGenerator.Generate(ApiLogggingBaseMessages.BadRequestMessage, __loggingResourceName),
  GetType(), GetCaller());
                return BadRequest("The supplied Accident was not found.");
            }


            try
            {
                if (await _dataAccessAuthoriser.AuthoriseAccessToClientData(principal, existingObjectInDb.Customer))
                {

                    if (ModelState.IsValid)
                    {

                        var theCustomer = existingObjectInDb.Customer;
                        var theAccident = existingObjectInDb;
                        //try and get the customer 
                        var theNotificationToSave = new ExternalNotification();
                        CustomerViewModel customer = null;
                        theNotificationToSave.Accident = existingObjectInDb;

                        //do something based on notification strategy:


                        //todo:replace with proper stragegy - all take return void as are command. 


                        if (notificaton.NotificationType == NotificationType.AccidentEmail)
                        {
                            theNotificationToSave.NotificationType = NotificationType.AccidentEmail;
                            //get address
                            var address = existingObjectInDb.Customer.EmergencyEmailContact;
                            theNotificationToSave.To = address;

                            if (!String.IsNullOrEmpty(address))
                            {
                                //automailer 
                                var respondants = new List<string>();
                                respondants.Add(address);


                                var GmailLessSecureMailService = new AxiappMailService();




                                if (
                                    GmailLessSecureMailService.SendMessage(respondants, "Axiapp - An accident has occurred",
                                        String.Format(
                                            "<h1>Oh my God, there's been a horrific smash at {0} and everyone's dead!</h1>",
                                            DateTime.Now)))
                                {
                                    theNotificationToSave.Result = "Success";
                                    theNotificationToSave.Created = DateTime.Now;


                                    var modelToReturn = TheModelFactoryV1.Create(await _repo.Add(theNotificationToSave));


                                   
                                        GenerateBaseLog(ApiLogType.Information,
                                            LogMessageGenerator.Generate(ApiLogggingBaseMessages.Created,
                                                __loggingResourceName),
                                            GetType(), GetCaller());
                                    return CreatedAtRoute("Notifications", new { id = modelToReturn.Id }, modelToReturn);
                                }
                                else //failed
                                {
                                    theNotificationToSave.Result = "Failed";
                                    theNotificationToSave.Created = DateTime.Now;


                                    var modelToReturn = TheModelFactoryV1.Create(await _repo.Add(theNotificationToSave));


                                   
                                        GenerateBaseLog(ApiLogType.Information,
                                            LogMessageGenerator.Generate(ApiLogggingBaseMessages.Created,
                                                __loggingResourceName),
                                            GetType(), GetCaller());
                                    return CreatedAtRoute("Notifications", new { id = modelToReturn.Id }, modelToReturn);
                                }



                            }

                            //NO EMAIL IN SYSTEM FOR EMERGENCY CONTACT
                           
                  GenerateBaseLog(ApiLogType.Warning,
  LogMessageGenerator.Generate(ApiLogggingBaseMessages.BadRequestMessage, __loggingResourceName),
  GetType(), GetCaller());
                            return BadRequest("There is no emergency email contact in the system so this request cannot be processed");

                        }

                        if (notificaton.NotificationType == NotificationType.AccidentSMS)
                        {
                            try
                            {

                                //validate
                                theNotificationToSave.NotificationType = NotificationType.AccidentSMS;

                                var key = "da8e48fd8f5bdfc705965646303a600bc02e8c7f";

                                string phoneNUmber = existingObjectInDb.Customer.EmergencySMSContact;
                                theNotificationToSave.To = phoneNUmber;
                                /*string phoneNUmber = "07476278909";*/
                                string removespaces = phoneNUmber.Replace(" ", String.Empty);

                                string nuewNumber;
                                if (phoneNUmber[0] == '0')
                                {
                                    nuewNumber = "44" + removespaces.Remove(0, 1);

                                }
                                else
                                {
                                    nuewNumber = removespaces;
                                }
                                //todo: check it's a proper number


                                string message = "Hello, there has been an accident. That's not good, is it?";
                                if (customer != null)
                                {
                                    message =
                                        String.Format(
                                            "Hello, there has been an accident involving {0} {1} {2} That's not good, is it?",
                                            customer.FirstName,
                                            customer.LastName);

                                }


                                var twilioClient = new TwilioClient();
                                twilioClient.SetupMessage(nuewNumber, message);
                                var msgSuccess = twilioClient.SendMessage();


                                /* Clockwork.API api = new API(key);
                                 SMSResult result = api.Send(
                                     new SMS
                                     {
                                         To = nuewNumber,
                                         Message = message
                                     });*/

                                if (msgSuccess)
                                {
                                    //todo:no content?? 
                                    theNotificationToSave.Result = "Success";
                                    theNotificationToSave.Created = DateTime.Now;

                                    var modelToReturn = TheModelFactoryV1.Create(await _repo.Add(theNotificationToSave));

                                   
                                    GenerateBaseLog(ApiLogType.Information,
                                       LogMessageGenerator.Generate(ApiLogggingBaseMessages.Created, __loggingResourceName),
                                       GetType(), GetCaller());
                                    return CreatedAtRoute("Notifications", new { id = modelToReturn.Id }, modelToReturn);
                                }
                                else
                                {

                                    var exception = new Exception("Couldn't send SMS notification");

                                   
                                    GenerateBaseLog(ApiLogType.Error,
        LogMessageGenerator.Generate(ApiLogggingBaseMessages.InternalServerErrorMessage, __loggingResourceName),
         GetType(), GetCaller(), exception);
                                    return InternalServerError(exception);


                                }
                            }
                            catch (Exception ex)
                            {
                               
                                GenerateBaseLog(ApiLogType.Error,
     LogMessageGenerator.Generate(ApiLogggingBaseMessages.InternalServerErrorMessage, __loggingResourceName),
      GetType(), GetCaller(), ex);
                                //todo:logging
                            }
                        }


                        if (notificaton.NotificationType == NotificationType.AccidentPDF)
                        {
                            //get address

                            try
                            {
                                theNotificationToSave.NotificationType = NotificationType.AccidentPDF;
                                customer = TheModelFactoryV1.Create(await customerRepo.Get(theCustomer.Id));

                                //todo: sort this out
                                var theAccidentSystem =
                                    _db.Accidents
                                        .FirstOrDefault(x=>x.Id == parsedAccidentId);
                                var accident = TheModelFactoryV1.Create(await accidentRepo.Get(theAccident.Id));

                                var otherDriver = _db.OtherDrivers.Where(x => x.Accident.Id == accident.Id)
                                    .Where(x => x.IsPrimary)
                                    .OrderByDescending(x => x.Created).ToList().FirstOrDefault();


                                if (otherDriver?.Email == null)
                                {
                                    return BadRequest("There is no other driver email in the system so this request cannot be processed");
                                }

                                var defendant = TheModelFactoryV1.Create(await otherDriversRepo.Get(otherDriver.Id));



                                if (defendant != null && customer != null && accident != null)
                                {
                                    //make sure we have somewhere to send it
                                    var defendantEmail = "";

                                    if (IsValidEmail(defendant.Email))
                                    {
                                        defendantEmail = defendant.Email;
                                    }
                                    //in case the email is in the wrong field.
                                    else if (IsValidEmail(defendant.Telephone))
                                    {
                                        defendantEmail = defendant.Telephone;
                                    }

                                    if (!String.IsNullOrEmpty(defendantEmail))
                                    //automailer 
                                    {
                                        var respondants = new List<string>();
                                        respondants.Add(defendantEmail);
                                        theNotificationToSave.To = defendantEmail;

                                        var GmailLessSecureMailService =
                                            new GmailLessSecureMailService("*****@*****.**", "Diagonal23",
                                                respondants,
                                                "Your Axiapp Accident Details Swap",
                                                GenerateAccidentHtml(customer, defendant, accident));

                                        if (GmailLessSecureMailService.SendEmail())

                                            theNotificationToSave.Result = "Success";
                                        theNotificationToSave.Created = DateTime.Now;

                                        var modelToReturn = TheModelFactoryV1.Create(await _repo.Add(theNotificationToSave));

                                       
                                        GenerateBaseLog(ApiLogType.Information,
                                           LogMessageGenerator.Generate(ApiLogggingBaseMessages.Created, __loggingResourceName),
                                           GetType(), GetCaller());
                                        return CreatedAtRoute("Notifications", new { id = modelToReturn.Id }, modelToReturn);
                                    }
                                }


                            }
                            catch (Exception ex)
                            {

                               
                                GenerateBaseLog(ApiLogType.Error,
    LogMessageGenerator.Generate(ApiLogggingBaseMessages.InternalServerErrorMessage, __loggingResourceName),
    GetType(), GetCaller(), ex);
                                return
                                    InternalServerError(
                                        new Exception("Couldn't process your notification properly", ex));
                            }

                        }

                    }
                   
                    GenerateBaseLog(ApiLogType.Warning,
    LogMessageGenerator.Generate(ApiLogggingBaseMessages.BadRequestMessage, __loggingResourceName),
    GetType(), GetCaller());
                    return BadRequest(ModelState);
                }

               
                GenerateBaseLog(ApiLogType.Error,
                  LogMessageGenerator.Generate(ApiLogggingBaseMessages.UnauthorisedAccess, __loggingResourceName),
                  GetType(), GetCaller());
                return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You are not authorised to access this resource."));
            }
            catch (Exception ex)
            {


                var exce = new Exception("Couldn't process your notification properly", ex);
               
                GenerateBaseLog(ApiLogType.Error,
    LogMessageGenerator.Generate(ApiLogggingBaseMessages.InternalServerErrorMessage, __loggingResourceName),
    GetType(), GetCaller(), exce);

                return InternalServerError(exce);
            }

        }