package com.thesis.centralserver.services;

import com.thesis.centralserver.entities.Device;
import com.thesis.centralserver.entities.OffloadingTask;
import com.thesis.centralserver.entities.OffloadingTaskStatus;
import com.thesis.centralserver.repositories.DeviceRepository;
import com.thesis.centralserver.repositories.OffloadingTaskRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OffloadingTaskServiceImpl implements OffloadingTaskService {

    private final OffloadingTaskRepository offloadingTaskRepository;
    private final DeviceRepository deviceRepository;

    public OffloadingTaskServiceImpl(OffloadingTaskRepository offloadingTaskRepository,
                                     DeviceRepository deviceRepository) {
        this.offloadingTaskRepository = offloadingTaskRepository;
        this.deviceRepository = deviceRepository;
    }

    @Override
    public List<OffloadingTask> getAllTasks() {
        return offloadingTaskRepository.findAll();
    }

    @Override
    public OffloadingTask markTaskCompleted(Long id) {
        return changeTaskStatus(offloadingTaskRepository.getOne(id), OffloadingTaskStatus.COMPLETED);
    }

    @Override
    public OffloadingTask markTaskFailed(Long id) {
        return changeTaskStatus(offloadingTaskRepository.getOne(id), OffloadingTaskStatus.FAILED);
    }

    private OffloadingTask changeTaskStatus(OffloadingTask offloadingTask,
                                            OffloadingTaskStatus offloadingTaskStatus) {

        offloadingTask.setStatus(offloadingTaskStatus);

        if (offloadingTaskStatus == OffloadingTaskStatus.COMPLETED) {
            Device buyer = offloadingTask.getBuyer();
            Device seller = offloadingTask.getSeller();

            buyer.setCurrencyUnitsAvailable((int) (buyer.getCurrencyUnitsAvailable() - offloadingTask.getCost()));
            seller.setCurrencyUnitsAvailable((int) (seller.getCurrencyUnitsAvailable() + offloadingTask.getCost()));

            deviceRepository.save(buyer);
            deviceRepository.save(seller);
        }

        return offloadingTaskRepository.save(offloadingTask);

    }

}
