/*
 * Copyright (C) 2013 Matthew Dawson <matthew@mjdsystems.ca>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package ca.mcmaster.cas.smtlibchecker;

import ca.mcmaster.cas.matlab2smt.BooleanVariableType;
import ca.mcmaster.cas.matlab2smt.MatlabParser;
import ca.mcmaster.cas.matlab2smt.SMTLIBGenerator;
import ca.mcmaster.cas.matlab2smt.VariableParser;
import ca.mcmaster.cas.tablularexpression.Cell;
import ca.mcmaster.cas.tablularexpression.HierarchcialGridCheckerGenerator;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 *
 * @author Matthew Dawson <matthew@mjdsystems.ca>
 */
final public class HierarchicalGridSMTLIBGenerator implements HierarchcialGridCheckerGenerator {

    public HierarchicalGridSMTLIBGenerator(VariableParser variableDefinitions) {
        m_variableDefinitions = variableDefinitions;
    }

    private String generateQueryPrefix() {
        if (!m_parentCellsCVC3Code.isEmpty()){
            String output = "(and ";
            output += StringUtils.join(m_parentCellsCVC3Code, " ") + " ";
            return output;
        }
        return "(and true ";
    }

    private void outputCells() {
        // First is disjoint testing.
        m_output += "(push 1)\n";

        String query = "(assert ";
        query += generateQueryPrefix();
        if (m_currentDisjointQueries.isEmpty()) {
            query += "false";
        } else if (m_currentDisjointQueries.size() == 1) {
            query += m_currentDisjointQueries.get(0);
        } else {
            query += "(or " + StringUtils.join(m_currentDisjointQueries, '\n') + ")";
        }
        query += "))";
        m_queries.add(query);
        m_output += query + "\n";

        m_output += "(check-sat)\n(pop 1)\n";

        // Next is complete.
        m_output += "(push 1)\n";

        query = "(assert ";
        query += generateQueryPrefix();
        query += "(not ";
        if (m_currentCompleteQueries.isEmpty()) {
            query += "true";
        } else if (m_currentCompleteQueries.size() == 1) {
            query +=  m_currentCompleteQueries.get(0);
        } else {
            query += "(or " + StringUtils.join(m_currentCompleteQueries, " ") + ")";
        }
        query += ")))";
        m_queries.add(query);
        m_output += query + "\n";

        m_output += "(check-sat)\n(pop 1)\n";

        m_currentlyRunning = false;

        // And finally clear the running list of current queries.
        m_currentCompleteQueries.clear();
        m_currentDisjointQueries.clear();
    }

    @Override
    public void descendIntoGridFromCell(Cell cell) {
        if (m_currentlyRunning) {
            outputCells();
        }
        m_parentCellsCVC3Code.addFirst(new MatlabParser(m_variableDefinitions, cell.contents()).getRootExpression().getCheckerOutput(m_CVC3Generator, m_booleanType));
        m_currentlyRunning = true;
    }

    @Override
    public void ascendFromGrid() {
        if (m_currentlyRunning) {
            outputCells();
        }
        m_parentCellsCVC3Code.removeFirst();
    }

    @Override
    public void handleEdgeCell(Cell cell) {
        handleLeafCell(cell);
    }

    @Override
    public void handleLeafCell(Cell cell) {
        // First get the appropriate CVC3 code from matlab.
        String newCellCode = new MatlabParser(m_variableDefinitions, cell.contents()).getRootExpression().getCheckerOutput(m_CVC3Generator, m_booleanType);

        // Next form the disjoint queries and add to the list.
        for(String otherCellCode : m_currentCompleteQueries) {
            String newDisjointQuery = "(and " + otherCellCode  + " " + newCellCode + ")";
            m_currentDisjointQueries.add(newDisjointQuery);
        }

        // Lastly add the cell to the list for the complete query
        m_currentCompleteQueries.add(newCellCode);
    }

    @Override
    public String getFinalString() {
        if (m_currentlyRunning) {
            outputCells();
        }
        return m_output;
    }

    public List<String> getFinalQueries() {
        if (m_currentlyRunning) {
            outputCells();
        }
        return m_queries;
    }

    Deque<String> m_parentCellsCVC3Code = new ArrayDeque<String>();

    List<String> m_currentDisjointQueries = new ArrayList<String>();
    List<String> m_currentCompleteQueries = new ArrayList<String>();

    boolean m_currentlyRunning = true;

    String m_output = "";
    List<String> m_queries = new ArrayList<String>();

    // To fix properly.
    VariableParser m_variableDefinitions;
    static BooleanVariableType m_booleanType = new BooleanVariableType();
    SMTLIBGenerator m_CVC3Generator = new SMTLIBGenerator();
}
