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

namespace JamesKovacs.IoCArticle.TopdownDependencies.Services {
    public class InvoiceService {
        private readonly AuthorizationService authoriazationService;
        private readonly InvoiceValidator invoiceValidator;
        private readonly InvoiceRepository 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);
        }
    }
}