/*
 * 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.cvc3generator;

import ca.mcmaster.cas.matlab2smt.MatlabParser;
import ca.mcmaster.cas.matlab2smt.BooleanVariableType;
import ca.mcmaster.cas.matlab2smt.VariableParser;
import ca.mcmaster.cas.matlab2smt.CVC3Generator;
import ca.mcmaster.cas.tablularexpression.Cell;
import ca.mcmaster.cas.tablularexpression.HierarchcialGridCheckerGenerator;
import java.util.ArrayList;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import org.apache.commons.lang3.StringUtils;

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

    public HierarchicalGridCVC3Generator(VariableParser variableDefinitions, int queryCountStart) {
        m_variableDefinitions = variableDefinitions;
        m_currentTCC = queryCountStart;
    }

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

    private void outputCells() {
        // First is disjoint testing.
        m_output += "ECHO \"begin" + m_currentTCC + "\";\n";
        m_output += "PUSH;\n";

        String query = "QUERY ";
        query += generateQueryPrefix();
        query += "(" + StringUtils.join(m_currentDisjointQueries, " AND\n");
        query += ");";
        m_queries.add(query);
        m_output += query + "\n";

        m_output += "POP;\n";
        m_output += "ECHO \"end" + m_currentTCC + "\";\n";

        // Finished first TCC, increment counter.
        m_currentTCC++;

        // Next is complete.
        m_output += "ECHO \"begin" + m_currentTCC + "\";\n";
        m_output += "PUSH;\n";

        query = "QUERY ";
        query += generateQueryPrefix();
        query += "(" + StringUtils.join(m_currentCompleteQueries, " OR ");
        query += ");";
        m_queries.add(query);
        m_output += query + "\n";

        m_output += "POP;\n";
        m_output += "ECHO \"end" + m_currentTCC + "\";\n";

        // Finished other TCC, increment counter.
        m_currentTCC++;

        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 = "NOT ( " + otherCellCode  + " AND " + 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;
    int m_currentTCC = 1;

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

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