/* fileid.cc
****************************************************************************************************************
****************************************************************************************************************

    Copyright (C) 2021, 2026 Askar Almatov

    This file is part of Trafficmeter.

    Trafficmeter is free software: you can redistribute it and/or modify it under the terms of the GNU General
    Public License as published by the Free Software Foundation, either version 3 of the License, or (at your
    option) any later version.

    Trafficmeter is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
    implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
    License for more details.

    You should have received a copy of the GNU General Public License along with Trafficmeter. If not, see
    <http://www.gnu.org/licenses/>.
*/

#include <algorithm>

#include "fileid.h"
#include "tmdefs.h"

using namespace trafficmeter;

using std::max;
using std::string;
using std::to_string;

constexpr const int     HASH_LENGTH_ = max( {SUFFIX_HASH_LENGTH, PREFIX_HASH_LENGTH} );

/**************************************************************************************************************/
FileId::FileId( int hash, time_t stem, int extension )
{
    static_assert( HASH_LENGTH_ + EXTENSION_LENGTH <= 32 );
    id_ = stem;
    id_ <<= HASH_LENGTH_;
    id_ += hash;
    id_ <<= EXTENSION_LENGTH;
    id_ += extension;
}

/**************************************************************************************************************/
int
FileId::hash() const
{
    return ( id_ >> EXTENSION_LENGTH ) & ( (1U << HASH_LENGTH_) - 1 );
}

/**************************************************************************************************************/
time_t
FileId::stem() const
{
    return id_ >> ( HASH_LENGTH_ + EXTENSION_LENGTH );
}

/**************************************************************************************************************/
int
FileId::extension() const
{
    return id_ & ( (1U << EXTENSION_LENGTH) - 1 );
}

/**************************************************************************************************************/
string
FileId::fileName() const
{
    string  fileName( to_string(stem()) );
    int&&   ext = extension();

    if ( ext > 0 )
    {
        fileName += '.' + to_string( ext );
    }

    return std::move( fileName );
}
