/*
 * 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.ApiResponse;
import io.swagger.annotations.ApiResponses;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpStatus;
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.application.service.SdmConfigService;
import com.scytl.products.ov.sdm.domain.model.sdmconfig.SdmConfigData;

@RestController
@RequestMapping("/sdm-ws-rest/sdm-config")
@Api(value = "SDM Configurations REST API")
public class SdmConfigResource {

	private static final Logger LOGGER = LoggerFactory.getLogger(SdmConfigResource.class);
	
	@Autowired
    private SdmConfigService sdmConfigService;

    @RequestMapping(method = RequestMethod.GET , produces = "application/json")
    @ApiOperation(value = "Get SDM configuration service", notes = "", response = String.class)
    @ApiResponses({@ApiResponse(code = 500, message = "Internal Server Error")})
    public ResponseEntity<?> getSdmConfig() {
        SdmConfigData config = new SdmConfigData();
        try {
            config.setConfig(sdmConfigService.getConfig());
        } catch (IOException e) {
        	LOGGER.error ("Error trying to get SDM configuration.", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
        return ResponseEntity.ok(config);
    }

    @RequestMapping(method = RequestMethod.GET , produces = "application/json",
    value = "/langs/{langCode}")
    @ApiOperation(value = "Get SDM language", notes = "", response = String.class)
    @ApiResponses({@ApiResponse(code = 500, message = "Internal Server Error")})
    public ResponseEntity<?> loadLanguage(@PathVariable(value = "langCode") String languageCode) {

        try {
            FileSystemResource languageFile = sdmConfigService.loadLanguage(languageCode);
            if (languageFile.exists()) {
                return ResponseEntity.ok(languageFile);
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }
        } catch (IllegalArgumentException e) {
        	LOGGER.info ("Error trying to get SDM language.", e);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.toString());
        }
    }
}
