/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.sdm.ui.ws.rs.application;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.scytl.products.ov.commons.beans.exceptions.ResourceNotFoundException;
import com.scytl.products.ov.sdm.application.service.TallySheetService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * The tally sheet end point
 */
@RestController
@RequestMapping("/sdm-ws-rest/tallysheet")
@Api(value = "Tallysheet REST API", description = "")
public class TallySheetResource {

	private static final String CSV_FILENAME = "tallysheet.csv";

	private static final String HEADER_KEY = "Content-Disposition";

	private static final String HEADER_VALUE = String.format("attachment; filename=\"%s\"", CSV_FILENAME);

    @Autowired
    private TallySheetService tallySheetService;

    /**
     * Returns an tally sheet identified by election event and its ballot box id.
     *
     * @param electionEventId the election event id.
     * @param ballotBoxId the ballot box id.
     * @return a tally sheet  identified by election event and its ballot box id.
     */
    @RequestMapping(value = "/electionevent/{electionEventId}/ballotbox/{ballotBoxId}", method = RequestMethod.GET, produces = "text/csv; charset=utf-8")
	@ApiOperation(value = "Get tallysheet", notes = "Service to retrieve the tallysheet of a given ballot box.", response = HttpServletResponse.class)
	public void downloadCSV(@ApiParam(value = "String", required = true) @PathVariable String electionEventId,
			@ApiParam(value = "String", required = true) @PathVariable String ballotBoxId, HttpServletResponse response)
					throws IOException, ResourceNotFoundException {

        response.setHeader(HEADER_KEY, HEADER_VALUE);

        tallySheetService.generate(response.getWriter(), electionEventId, ballotBoxId);
    }
}
