package ru.yandex.webmaster3.core.semantic.data_reactor_common.impl.processors.schemaorg.rating;

import ru.yandex.common.util.collections.Cf;
import ru.yandex.webmaster3.core.semantic.data_reactor_common.Entity;
import ru.yandex.webmaster3.core.semantic.data_reactor_common.EntityProcessor;
import ru.yandex.webmaster3.core.semantic.data_reactor_common.impl.BaseMutableEntity;
import ru.yandex.webmaster3.core.semantic.data_reactor_common.impl.attrs.StringAttrValue;

import java.util.Collection;

/**
 * Created by aleksart on 19.02.14.
 */
public class RatingNormalizationProcessor extends EntityProcessor{


    public static String[] getRatingNormalization(String sbest, String sworst, String sval){

        Float val = null;
        try{
            val = Float.valueOf(sval);

        } catch (NullPointerException e){
            return new String[2];
        }
        Float best = null;
        Float worst = null;

        try{
            best = Float.valueOf(sbest);

            worst = Float.valueOf(sworst);
        } catch(Exception e){

        }

        best = best == null ? 5 : best;

        worst = worst == null ? 1 : worst;

        String[] result = new String[2];
        if (val < worst || val > best || worst.equals(best)) {
            throw new IllegalArgumentException("Value out of bound");
        }
        if ((best == 1) && (worst == -1)) {
            result[0] = String.valueOf(Math.round(val));
            result[1] = "ATTITUDE";
        } else if (best == 5 && worst == 1) {
            result[0] = String.valueOf(Math.round(val));
            result[1] = "RATING5";
        } else {
            result[0] = String.valueOf(Math.round((val - worst) / (best - worst) * 9) + 1);
            result[1] = "RATING10";
        }
        return result;

    }

    @Override
    public Collection<Entity> process(Entity e) {
        String name = null;
        String best = null;
        String worst = null;
        String val = null;
        try{
            name = e.getStringValue("name");
        } catch (Exception exc){

        }
        try{
            best = e.getStringValue("best");
        } catch (Exception exc){

        }
        try{
            worst = e.getStringValue("worst");
        } catch (Exception exc){

        }
        try{
            val = e.getStringValue("value");
        } catch (Exception exc){

        }

        String[] normVals = getRatingNormalization(best,worst,val);
        val = normVals[0]; String type = normVals[1];
        Entity result =  new BaseMutableEntity("rating",e.getUrl());
        result.appendValue("type", new StringAttrValue(type));
        result.appendValue("val", new StringAttrValue(val));
        result.appendValue("name", new StringAttrValue(name));
        return Cf.list(result);
    }
}
