package org.artisanlogiciel.lua;

import java.util.*;

public class LuaSequence
extends  LuaObject{
    List<LuaObject> items;

    public LuaSequence()
    {
        items = new ArrayList<>();
    }

    void addObject(LuaObject object)
    {
        if ( object == null )
        {
            System.err.println("adding null tuple");
        }
        items.add(object);
    }

    public boolean isMap()
    {
        return ( items.get(0) instanceof LuaTuple );
    }

    public HashMap<String,Object> wrapTodHashMap()
    {
        HashMap<String,Object> map = new HashMap<>(items.size());

        for ( LuaObject item : items)
        {
            if (item instanceof LuaTuple )
            {
                LuaTuple tuple = (LuaTuple) item;
                tuple.addInMap(map);
            }
        }

        return map;
    }

    public List<Object> wrapToList()
    {
        List<Object> list = new ArrayList<>() ;
        for ( LuaObject item : items)
        {
            if ( ! (item instanceof LuaTuple ) )
            {
                list.add(item.wrapToJava());
            }
        }
        return list;
    }

    @Override
    public Object wrapToJava() {
        return isMap() ? wrapTodHashMap() : wrapToList();
    }

    @Override
    public String toString()
    {
        StringBuffer buffer = new StringBuffer();
        buffer.append('{');
        if (items.size() > 0) {
            buffer.append(items.get(0).toString());
            if (items.size() > 1) {
                for (int i = 1; i < items.size(); i ++)
                {
                    buffer.append(',');
                    buffer.append(items.get(i).toString());
                }
            }
        }
        buffer.append('}');
        return buffer.toString();
    }
}
