/*
 * Copyright (c) 2022 MiLaboratories Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.milaboratory.util.sorting;

import java.util.function.Function;

public final class MappedSortingProperty<T2, T1> implements SortingProperty<T2> {
    private final SortingProperty<T1> prop;
    private final Function<T2, T1> mapping;

    public MappedSortingProperty(SortingProperty<T1> prop, Function<T2, T1> mapping) {
        this.prop = prop;
        this.mapping = mapping;
    }

    @Override
    public Object get(T2 obj) {
        return prop.get(mapping.apply(obj));
    }

    @Override
    public int compare(T2 o1, T2 o2) {
        T1 oo1 = mapping.apply(o1);
        T1 oo2 = mapping.apply(o2);
        return prop.compare(oo1, oo2);
    }

    @Override
    public SortingPropertyRelation relationTo(SortingProperty<?> other) {
        if (!(other instanceof MappedSortingProperty))
            return SortingPropertyRelation.None;
        if (mapping.equals(((MappedSortingProperty<?, ?>) other).mapping))
            return SortingPropertyRelation.None;
        return prop.relationTo(((MappedSortingProperty<?, ?>) other).prop);
    }
}
