/*******************************************************************************
 * Copyright 2016 Sistcoop, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package org.openfact.services.resources.admin;

import org.jboss.resteasy.annotations.cache.NoCache;
import org.openfact.common.ClientConnection;
import org.openfact.events.admin.OperationType;
import org.openfact.models.OpenfactSession;
import org.openfact.models.OrganizationModel;
import org.openfact.models.ubl.InvoiceModel;
import org.openfact.models.utils.ModelToRepresentation;
import org.openfact.representations.idm.ubl.InvoiceRepresentation;
import org.openfact.representations.idm.ubl.common.InvoiceLineRepresentation;
import org.openfact.services.ErrorResponse;
import org.openfact.services.ServicesLogger;
import org.openfact.services.managers.InvoiceManager;

import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.util.List;
import java.util.stream.Collectors;

public class InvoiceAdminResource {

    private static final ServicesLogger logger = ServicesLogger.LOGGER;

    protected OrganizationModel organization;
    protected InvoiceModel invoice;
    @Context
    protected UriInfo uriInfo;
    @Context
    protected OpenfactSession session;
    @Context
    protected ClientConnection clientConnection;
    @Context
    protected HttpHeaders headers;
    private OrganizationAuth auth;
    private AdminEventBuilder adminEvent;

    public InvoiceAdminResource(OrganizationModel organization, OrganizationAuth auth,
                                AdminEventBuilder adminEvent, InvoiceModel invoice) {
        this.auth = auth;
        this.organization = organization;
        this.adminEvent = adminEvent;
        this.invoice = invoice;

        auth.init(OrganizationAuth.Resource.INVOICE);
    }

    /**
     * Get the invoice with the specified invoiceId.
     *
     * @return The invoice with the specified invoiceId
     * @summary Get the invoice with the specified invoiceId
     */
    @GET
    @NoCache
    @Produces(MediaType.APPLICATION_JSON)
    public InvoiceRepresentation getInvoice(@QueryParam("includeXml") boolean includeXml) {
        auth.requireView();

        if (invoice == null) {
            throw new NotFoundException("Invoice not found");
        }

        InvoiceRepresentation rep = ModelToRepresentation.toRepresentation(invoice, includeXml);
        return rep;
    }

    @GET
    @Path("lines")
    @Produces(MediaType.APPLICATION_JSON)
    public List<InvoiceLineRepresentation> getLines() {
        auth.requireView();

        return invoice.getInvoiceLine().stream().map(f -> ModelToRepresentation.toRepresentation(f))
                .collect(Collectors.toList());
    }

    /**
     * Deletes invoice with given invoiceId.
     *
     * @throws AuthorizationException
     *             The user is not authorized to delete this invoice.
     */
    @DELETE
    public Response deleteInvoice() {
        auth.requireManage();

        if (invoice == null) {
            throw new NotFoundException("Invoice not found");
        }

        boolean removed = new InvoiceManager(session).removeInvoice(organization, invoice);
        if (removed) {
            adminEvent.operation(OperationType.DELETE).resourcePath(uriInfo).success();
            return Response.noContent().build();
        } else {
            return ErrorResponse.error("Invoice couldn't be deleted", Response.Status.BAD_REQUEST);
        }
    }

}

@@ -885,16 +885,59 @@
 admin;%0A%0A
+import org.apache.commons.lang.ArrayUtils;%0A
 import o
@@ -1022,24 +1022,75 @@
 Connection;%0A
+import org.openfact.common.converts.DocumentUtils;%0A
 import org.o
@@ -1125,16 +1125,59 @@
 onType;%0A
+import org.openfact.models.ModelException;%0A
 import o
@@ -1646,16 +1646,45 @@
 Manager;
+%0Aimport org.w3c.dom.Document;
 %0A%0Aimport
@@ -3237,24 +3237,739 @@
 rep;%0A    %7D%0A%0A
+    @GET%0A    @Path(%22xml%22)%0A    @NoCache%0A    @Produces(%22application/xml%22)%0A    public Response getInvoiceAsXml() %7B%0A        auth.requireView();%0A%0A        if (invoice == null) %7B%0A            throw new NotFoundException(%22Invoice not found%22);%0A        %7D%0A%0A        Document document = null;%0A        try %7B%0A            document = DocumentUtils.byteToDocument(ArrayUtils.toPrimitive(invoice.getXmlDocument()));%0A        %7D catch (Exception e) %7B%0A            return ErrorResponse.exists(%22Invalid xml%22);%0A        %7D%0A%0A        Response.ResponseBuilder response = Response.ok((Object) document);%0A        response.header(%22Content-Disposition%22, %22attachment; filename=%5C%22%22 + invoice.getID() + %22.xml%5C%22%22);%0A        return response.build();%0A    %7D%0A%0A
     @GET%0A   
@@ -4367,27 +4367,8 @@
 tion
-%0A     *            
  The

add xml download endpoint