using System.Security;
using JamesKovacs.IoCArticle.DependencyInversion.Domain;
using JamesKovacs.IoCArticle.DependencyInversion.Repositories;

namespace JamesKovacs.IoCArticle.DependencyInversion.Services {
    public class InvoiceService : IInvoiceService {
        private readonly IAuthorizationService authoriazationService;
        private readonly IInvoiceValidator invoiceValidator;
        private readonly IInvoiceRepository invoiceRepository;

        public InvoiceService() {
            authoriazationService = new AuthorizationService();
            invoiceValidator = new InvoiceValidator();
            invoiceRepository = new InvoiceRepository();
        }

        public ValidationResults Submit(Invoice invoice) {
            ValidationResults results;
            CheckPermissions(invoice, InvoiceAction.Submit);
            results = ValidateInvoice(invoice);
            SaveInvoice(invoice);
            return results;
        }

        private void CheckPermissions(Invoice invoice, InvoiceAction action) {
            if(authoriazationService.IsActionAllowed(invoice, action) == false) {
                throw new SecurityException("Insufficient permissions to submit this invoice");
            }
        }

        private ValidationResults ValidateInvoice(Invoice invoice) {
            return invoiceValidator.Validate(invoice);
        }

        private void SaveInvoice(Invoice invoice) {
            invoiceRepository.Save(invoice);
        }
    }
}