package com.rthoni.intellij.codefromds.dbo.options;

import com.intellij.database.model.DasTable;
import com.intellij.database.util.DasUtil;
import com.rthoni.intellij.codefromds.business.Helper;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import java.util.stream.Collectors;

/**
 * Created by robin on 11/15/16.
 */
public class TableSelection {

    private DasTable _table;

    private List<ColumnSelection> _columns;

    public TableSelection(DasTable table)
    {
        _table = table;
        _columns = DasUtil.getColumns(table).toList().stream().map(ColumnSelection::new).collect(Collectors.toList());
    }

    public HashMap<String, Object> toMap()
    {
        HashMap<String, Object> map = new HashMap<>();

        map.put("table", _table == null ? null : _table.getName());
        List<Object> tables = new Vector<>();
        for (ColumnSelection col : _columns) {
            tables.add(col.toMap());
        }
        map.put("columns", tables);

        return map;
    }

    public void fromJson(JSONObject json)
    {
        JSONArray array = json.getJSONArray("columns");
        for (ColumnSelection column : _columns) {
            JSONObject obj = Helper.findColumnInJson(array, column.getColumn().getName());
            if (obj != null) {
                column.fromJson(obj);
            } else {
                column.setSelected(false);
            }
        }
    }

    public DasTable getTable() {
        return _table;
    }

    public void setTable(DasTable table) {
        _table = table;
    }

    public List<ColumnSelection> getColumns() {
        return _columns;
    }

    public void setColumns(List<ColumnSelection> columns) {
        _columns = columns;
    }

    public boolean hasNone()
    {
        return _columns != null && _columns.stream().filter(ColumnSelection::isSelected).count() == 0;
    }

    public boolean hasAll()
    {
        return _columns != null && _columns.stream().filter(ColumnSelection::isSelected).count() == _columns.size();
    }
}
