/*
 * 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.infrastructure.service.impl;

import javax.json.Json;
import javax.json.JsonObjectBuilder;

import com.scytl.products.ov.sdm.domain.model.status.SynchronizeStatus;
import org.springframework.stereotype.Service;

import com.scytl.products.ov.sdm.domain.model.EntityRepository;
import com.scytl.products.ov.sdm.infrastructure.JsonConstants;
import com.scytl.products.ov.sdm.infrastructure.service.ConfigurationEntityStatusService;

/**
 * This class manages the status of a configuration entity. As we are working with entity in format json, the type is
 * string.
 */
@Service
public class ConfigurationEntityStatusServiceImpl implements ConfigurationEntityStatusService {

	/**
	 * @see com.scytl.products.ov.sdm.infrastructure.service.ConfigurationEntityStatusService#update(java.lang.String,
	 *      java.lang.String, com.scytl.products.ov.sdm.domain.model.EntityRepository)
	 */
	@Override
	public String update(String newStatus, String id, EntityRepository repository) {
		JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
		jsonObjectBuilder.add(JsonConstants.JSON_ATTRIBUTE_NAME_ID, id);
		jsonObjectBuilder.add(JsonConstants.JSON_ATTRIBUTE_NAME_STATUS, newStatus);
		jsonObjectBuilder.add(JsonConstants.JSON_ATTRIBUTE_NAME_SYNCHRONIZED, Boolean.FALSE.toString());
		return repository.update(jsonObjectBuilder.build().toString());
	}

	/**
	 * @see com.scytl.products.ov.sdm.infrastructure.service.ConfigurationEntityStatusService#updateWithSynchronizedStatus(String, String, com.scytl.products.ov.sdm.domain.model.EntityRepository, com.scytl.products.ov.sdm.domain.model.status.SynchronizeStatus)
	 */
	@Override
	public String updateWithSynchronizedStatus(String newStatus, String id, EntityRepository repository,
			SynchronizeStatus syncDetails) {
		JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
		jsonObjectBuilder.add(JsonConstants.JSON_ATTRIBUTE_NAME_ID, id);
		jsonObjectBuilder.add(JsonConstants.JSON_ATTRIBUTE_NAME_STATUS, newStatus);
		jsonObjectBuilder.add(JsonConstants.JSON_ATTRIBUTE_NAME_SYNCHRONIZED,syncDetails.getIsSynchronized().toString());
		jsonObjectBuilder.add(JsonConstants.JSON_ATTRIBUTE_NAME_DETAILS, syncDetails.getStatus() );
		return repository.update(jsonObjectBuilder.build().toString());
	}

}
