/*
 * Copyright (c) 2018-2020, Andreas Kling <andreas@ladybird.org>
 * Copyright (c) 2021, Tobias Christiansen <tobyase@serenityos.org>
 * Copyright (c) 2021-2023, Sam Atkins <atkinssj@serenityos.org>
 * Copyright (c) 2022-2023, MacDue <macdue@dueutil.tech>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "PositionStyleValue.h"
#include <LibWeb/CSS/Enums.h>

namespace Web::CSS {

ValueComparingNonnullRefPtr<PositionStyleValue const> PositionStyleValue::create(ValueComparingNonnullRefPtr<EdgeStyleValue const> edge_x, ValueComparingNonnullRefPtr<EdgeStyleValue const> edge_y)
{
    return adopt_ref(*new (nothrow) PositionStyleValue(move(edge_x), move(edge_y)));
}

ValueComparingNonnullRefPtr<PositionStyleValue const> PositionStyleValue::create_center()
{
    return adopt_ref(*new (nothrow) PositionStyleValue(
        EdgeStyleValue::create(PositionEdge::Center, {}),
        EdgeStyleValue::create(PositionEdge::Center, {})));
}

ValueComparingNonnullRefPtr<PositionStyleValue const> PositionStyleValue::create_computed_center()
{
    return adopt_ref(*new (nothrow) PositionStyleValue(
        EdgeStyleValue::create({}, PercentageStyleValue::create(Percentage { 50 })),
        EdgeStyleValue::create({}, PercentageStyleValue::create(Percentage { 50 }))));
}

bool PositionStyleValue::is_center(SerializationMode mode) const
{
    return edge_x()->is_center(mode) && edge_y()->is_center(mode);
}

CSSPixelPoint PositionStyleValue::resolved(Layout::Node const& node, CSSPixelRect const& rect) const
{
    // Note: A preset + a none default x/y_relative_to is impossible in the syntax (and makes little sense)
    CSSPixels x = LengthPercentage::from_style_value(m_properties.edge_x->offset()).to_px(node, rect.width());
    CSSPixels y = LengthPercentage::from_style_value(m_properties.edge_y->offset()).to_px(node, rect.height());
    return CSSPixelPoint { rect.x() + x, rect.y() + y };
}

ValueComparingNonnullRefPtr<StyleValue const> PositionStyleValue::absolutized(ComputationContext const& computation_context) const
{
    return PositionStyleValue::create(
        edge_x()->absolutized(computation_context)->as_edge(),
        edge_y()->absolutized(computation_context)->as_edge());
}

void PositionStyleValue::serialize(StringBuilder& builder, SerializationMode mode) const
{
    m_properties.edge_x->serialize(builder, mode);
    builder.append(' ');
    m_properties.edge_y->serialize(builder, mode);
}

}
