/* 
-*- coding: latin-1 -*-

This file is part of RefactorErl.

RefactorErl is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

RefactorErl 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with RefactorErl.  If not, see <http://plc.inf.elte.hu/erlang/>.

The Original Code is RefactorErl.

The Initial Developer of the Original Code is Eötvös Loránd University.
Portions created  by Eötvös Loránd University and ELTE-Soft Ltd.
are Copyright 2007-2025 Eötvös Loránd University, ELTE-Soft Ltd.
and Ericsson Hungary. All Rights Reserved.
*/

package com.refactorerl.ui.logic.queries;

import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.logging.Logger;

import com.ericsson.otp.erlang.OtpErlangAtom;
import com.ericsson.otp.erlang.OtpErlangList;
import com.ericsson.otp.erlang.OtpErlangObject;
import com.ericsson.otp.erlang.OtpErlangString;
import com.ericsson.otp.erlang.OtpErlangTuple;
import com.refactorerl.ui.communication.ReferlProxy;
import com.refactorerl.ui.communication.exceptions.CommunicationException;
import com.refactorerl.ui.communication.exceptions.ConnectionException;
import com.refactorerl.ui.communication.exceptions.RequestException;
import com.refactorerl.ui.logic.AbstractRequest;
import com.refactorerl.ui.logic.DatabaseHashRequest;

public class QueryRequest extends AbstractRequest<SortedMap<String, List<QueryResultElement>>> {

	private String filePath;
	private Integer position;
	private String query;
	private boolean insertToHistory;

	public QueryRequest(String filePath, Integer position, String query, boolean insertToHistory, ReferlProxy proxy, Logger logger) {
		super(proxy, logger);
		this.filePath = filePath;
		this.position = position;
		this.query = query;
		this.insertToHistory = insertToHistory;
	}

	// moved to the execute methods
	public QueryRequest(String filePath, String query, boolean insertToHistory, ReferlProxy proxy, Logger logger) {
		this(filePath, null, query, insertToHistory, proxy, logger);
	}

	public QueryRequest(String query, boolean insertToHistory, ReferlProxy proxy, Logger logger) {
		this(null, null, query, insertToHistory, proxy, logger);
	}

	@Override
	public SortedMap<String, List<QueryResultElement>> execute() throws RequestException, ConnectionException,
			CommunicationException {
		OtpErlangList otpResults = new InternalQueryRequest(filePath, position, query, proxy, logger).execute();
		SortedMap<String, List<QueryResultElement>> results = processQueryResult(otpResults);

		OtpErlangTuple dbHash = new DatabaseHashRequest(proxy, logger).execute();

		if (insertToHistory)
			new InsertToQueryHistoryRequest(query, filePath, position, otpResults, "none", proxy.getNodeName(), dbHash, //$NON-NLS-1$
					proxy, logger).execute();

		return results;
	}

	protected static SortedMap<String, List<QueryResultElement>> processQueryResult(OtpErlangList resultList) {

		// ArrayList<QueryResult> queryResult = new ArrayList<QueryResult>();
		SortedMap<String, List<QueryResultElement>> queryResults = new TreeMap<>();

		for (OtpErlangObject element : resultList) {
			// QueryResult toAdd = new QueryResult();
			String name = ""; //$NON-NLS-1$
			List<QueryResultElement> queryElements = new ArrayList<>();

			OtpErlangTuple result = (OtpErlangTuple) element;

			if (result.elementAt(0).toString().equals("group_by")) { // one //$NON-NLS-1$
																		// level
																		// query
				OtpErlangTuple group = (OtpErlangTuple) result.elementAt(1);

				// toAdd.setId(group.elementAt(1).toString());

				name = group.elementAt(1).toString();

				OtpErlangAtom queryType = (OtpErlangAtom) result.elementAt(2);

				if (queryType.equals(new OtpErlangAtom("list"))) { //$NON-NLS-1$
					processListResult(queryElements, result);
				} else if (queryType.equals(new OtpErlangAtom("eq"))) { //$NON-NLS-1$

					queryElements.add(new QueryResultElement(result.elementAt(3).toString(), result.elementAt(4)
							.toString()));
				}
			} else {
				// toAdd.add(result.elementAt(1).toString());
				name = "Results"; //$NON-NLS-1$
				for (OtpErlangObject info : (OtpErlangList) result.elementAt(1)) {

					OtpErlangTuple elem = (OtpErlangTuple) info;

					String nodeValue = ((OtpErlangString) elem.elementAt(1)).toString();

					if (elem.elementAt(0) instanceof OtpErlangTuple) {
						OtpErlangTuple file = (OtpErlangTuple) elem.elementAt(0);
						String fileAbsPath = ((OtpErlangString) file.elementAt(0)).stringValue();
						int startPos = Integer.parseInt(file.elementAt(1).toString());
						int endPos = Integer.parseInt(file.elementAt(2).toString());

						// toAdd.add(fileAbsPath, startPos, endPos, nodeValue);
						queryElements.add(new QueryResultElement(fileAbsPath, startPos, endPos, nodeValue));

					} else { // nopos
						// toAdd.add(nodeValue);
						queryElements.add(new QueryResultElement(nodeValue));
					}
				}

				// queryElements.add(new
				// QueryResultElement(result.elementAt(1).toString()));
			}

			// queryResult.add(toAdd);
			queryResults.put(name, queryElements);
		}

		return queryResults;

	}

	private static void processListResult(List<QueryResultElement> queryElements, OtpErlangTuple result) {
		for (OtpErlangObject info : (OtpErlangList) result.elementAt(3)) {

			OtpErlangTuple elem = (OtpErlangTuple) info;

			String nodeValue = ((OtpErlangString) elem.elementAt(1)).toString();

			if (elem.elementAt(0) instanceof OtpErlangTuple) {
				OtpErlangTuple file = (OtpErlangTuple) elem.elementAt(0);
				String fileAbsPath = ((OtpErlangString) file.elementAt(0)).stringValue();
				int startPos = Integer.parseInt(file.elementAt(1).toString());
				int endPos = Integer.parseInt(file.elementAt(2).toString());

				// toAdd.add(fileAbsPath, startPos, endPos,
				// nodeValue);
				queryElements.add(new QueryResultElement(fileAbsPath, startPos, endPos, nodeValue));

			} else { // nopos
				// toAdd.add(nodeValue);
				queryElements.add(new QueryResultElement(nodeValue));
			}
		}
	}

	@Override
	protected OtpErlangObject doGetRequest() {
		return null;
	}

	@Override
	protected SortedMap<String, List<QueryResultElement>> doProcessReply(OtpErlangObject m) throws RequestException {
		return null;
	}

}
