// Copyright (C) 2018 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
//

#include <utility>
#include <xml_net_builder.hpp>
#include <details/ie_exception.hpp>
#include <algorithm>

using namespace ::testing;

IDManager* IDManager::_instance = nullptr;
size_t  IDManager::portID = 0;
size_t  IDManager::layerID = 0;

IDManager* IDManager::getInstance() {
    if (!_instance) {
        _instance = new IDManager();
    }
    return _instance;
}

size_t  IDManager::getNextLayerID() {
    return layerID++;
}

size_t  IDManager::getNextPortID() {
    return portID++;
}

void IDManager::reset() {
    portID = layerID = 0;
}

LayerDesc::LayerDesc(std::string type, InOutData& shapes) : _type(std::move(type)) {
    auto idManager = IDManager::getInstance();
    _layerID = idManager->getNextLayerID();
    auto inDims = shapes.inDims;
    auto outDims = shapes.outDims;
    for (const auto& inDim : inDims) {
        _inPortsID.emplace_back(idManager->getNextPortID(), inDim);
    }
    for (const auto& outDim : outDims) {
        _outPortsID.emplace_back(idManager->getNextPortID(), outDim);
    }
}

void LayerDesc::resetPortIDs() {
    _currentInPort = _currentOutPort = 0;
}

LayerDesc::LayerPortData LayerDesc::getNextInData() {
    if (_currentInPort == _inPortsID.size())
        THROW_IE_EXCEPTION << "Failed to get next input port: reached the last one";
    return _inPortsID[_currentInPort++];
}

LayerDesc::LayerPortData LayerDesc::getNextOutData() {
    if (_currentOutPort == _outPortsID.size())
        THROW_IE_EXCEPTION << "Failed to get next output port: reached the last one";
    return _outPortsID[_currentOutPort++];
}

size_t  LayerDesc::getLayerID() const {
    return _layerID;
}

size_t LayerDesc::getInputsSize() const {
    return _inPortsID.size();
}

size_t LayerDesc::getOutputsSize() const {
    return _outPortsID.size();
}

std::string LayerDesc::getLayerName() const {
    return _type + std::to_string(getLayerID());
}


EdgesBuilder& EdgesBuilder::connect(size_t  layer1, size_t  layer2) {
    auto found1 = std::find_if(layersDesc.begin(), layersDesc.end(), [&layer1](const LayerDesc::Ptr& desc) {
        return desc->getLayerID() == layer1;
    });
    auto found2 = std::find_if(layersDesc.begin(), layersDesc.end(), [&layer2](const LayerDesc::Ptr& desc) {
        return desc->getLayerID() == layer2;
    });
    if (found1 == layersDesc.end() || found2 == layersDesc.end())
        THROW_IE_EXCEPTION << "Failed to find layers with index: " << layer1 << " and " << layer2;

    nodeEdges.node("edge")
            .attr("from-layer", (*found1)->getLayerID())
            .attr("from-port", (*found1)->getNextOutData().portID)
            .attr("to-layer", (*found2)->getLayerID())
            .attr("to-port", (*found2)->getNextInData().portID).close();
    return *this;
}

std::string EdgesBuilder::finish() {
    auto& exp = nodeEdges.close();
    return exp;
}
