/*
 * 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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
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 java.io.IOException;

import com.scytl.products.ov.sdm.domain.model.generator.DataGeneratorProgressResponse;
import com.scytl.products.ov.sdm.domain.service.ProgressManagerService;


/**
 * The progress end-point. This class is here to maintain compatibility with the FE
 */
@RestController
@RequestMapping("/sdm-ws-rest/progress")
@Api(value = "Progress Manager REST API", description = "")
public class ProgressManagerResource {

    // The configuration of contests / elections
    @Value("${elections.config.filename}")
    private String configFile;

    @Autowired
    private ProgressManagerService<DataGeneratorProgressResponse> progressManagerService;

    /**
     * Get progress value of voting card sets.
     *
     * @return percentage of progress
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/json")
    @ApiOperation(value = "get progress", notes = "Service to get progress of a process.", response = Integer.class)
    @ApiResponses(value = {@ApiResponse(code = 404, message = "Not Found")})
    public ResponseEntity<DataGeneratorProgressResponse> progress(
            @ApiParam(value = "String", required = true) @PathVariable final String id) throws IOException {
        //code to maintain backwards compatibility with FE
        final DataGeneratorProgressResponse progress = progressManagerService.getForJob(id);
        //if some module fails to register for progress update we'll get a null here. protect against npe.
        if(progress != null) {
            return ResponseEntity.ok(progress);
        } else {
            return ResponseEntity.ok(new DataGeneratorProgressResponse());
        }
    }
}
