// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include "inc/Core/VectorSet.h"

using namespace SPTAG;

#pragma warning(disable:4996)  // 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

VectorSet::VectorSet()
{
}


VectorSet::~VectorSet()
{
}


BasicVectorSet::BasicVectorSet(const ByteArray& p_bytesArray,
                               VectorValueType p_valueType,
                               SizeType p_dimension,
                               SizeType p_vectorCount)
    : m_data(p_bytesArray),
      m_valueType(p_valueType),
      m_dimension(p_dimension),
      m_vectorCount(p_vectorCount),
      m_perVectorDataSize(static_cast<SizeType>(p_dimension * GetValueTypeSize(p_valueType)))
{
}


BasicVectorSet::~BasicVectorSet()
{
}


VectorValueType
BasicVectorSet::GetValueType() const
{
    return m_valueType;
}


void*
BasicVectorSet::GetVector(IndexType p_vectorID) const
{
    if (p_vectorID < 0 || static_cast<SizeType>(p_vectorID) >= m_vectorCount)
    {
        return nullptr;
    }

    SizeType offset = static_cast<SizeType>(p_vectorID) * m_perVectorDataSize;
    return reinterpret_cast<void*>(m_data.Data() + offset);
}


void*
BasicVectorSet::GetData() const
{
    return reinterpret_cast<void*>(m_data.Data());
}

SizeType
BasicVectorSet::Dimension() const
{
    return m_dimension;
}


SizeType
BasicVectorSet::Count() const
{
    return m_vectorCount;
}


bool
BasicVectorSet::Available() const
{
    return m_data.Data() != nullptr;
}


ErrorCode 
BasicVectorSet::Save(const std::string& p_vectorFile) const
{
    FILE * fp = fopen(p_vectorFile.c_str(), "wb");
    if (fp == NULL) return ErrorCode::FailedOpenFile;

    fwrite(&m_vectorCount, sizeof(int), 1, fp);
    fwrite(&m_dimension, sizeof(int), 1, fp);

    fwrite((const void*)(m_data.Data()), m_data.Length(), 1, fp);
    fclose(fp);
    return ErrorCode::Success;
}
