package org.wso2.carbon.device.mgt.ios.services.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.ios.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.ios.exception.*;
import org.wso2.carbon.device.mgt.ios.services.OperationManagementService;
import org.wso2.carbon.device.mgt.ios.api.utils.beans.OperationStatusBean;
import org.wso2.carbon.device.mgt.ios.api.utils.util.Message;
import org.wso2.carbon.device.mgt.ios.util.DeviceUtils;
import org.wso2.carbon.device.mgt.ios.util.IOSServiceUtils;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/operation")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class OperationManagementServiceImpl implements OperationManagementService {

    private static final Log log = LogFactory.getLog(OperationManagementServiceImpl.class);

    @PUT
    @Produces({ MediaType.APPLICATION_JSON })
    @Path("/{id}")
    public Response updateOperationStatus(@HeaderParam("Accept") String acceptHeader,
                                          @PathParam("id") String deviceId,
                                          OperationStatusBean operationStatusBean) {

        if (log.isDebugEnabled()) {
            log.debug("Requesting device information from " + deviceId);
        }

        if (operationStatusBean == null) {
            String errorMessage = "The payload of the iOS OperationStatus is incorrect.";
            log.error(errorMessage);
            throw new org.wso2.carbon.device.mgt.ios.exception.BadRequestException(
                    new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(errorMessage).build());
        }
        DeviceUtils deviceUtils = new DeviceUtils();
        DeviceIdentifier deviceIdentifier = deviceUtils.fetchDeviceIdentifierInstance(deviceId);

        try {
            Operation operation = new Operation();
            if (operationStatusBean.getStatus().toString().equals(Operation.Status.COMPLETED.toString())) {
                operation.setStatus(Operation.Status.COMPLETED);
            }
            if (operationStatusBean.getOperationId() != null) {
                operation.setId(Integer.parseInt(operationStatusBean.getOperationId()));
            }
            IOSServiceUtils.getDeviceManagementService().updateOperation(deviceIdentifier, operation);
            return Response.status(Response.Status.OK).entity("IOS OperationStatus updated successfully.").build();

        } catch (DeviceManagementException e) {
            String msg = "Error occurred when fetching device id " + deviceId;
            log.error(msg, e);
            throw new UnexpectedServerErrorException(
                    new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
        } catch (OperationManagementException e) {
            String msg = "Error occurred when fetching device id " + deviceId;
            log.error(msg, e);
            throw new UnexpectedServerErrorException(
                    new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
        }
    }
}