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

import com.ericsson.otp.erlang.OtpErlangAtom;
import com.ericsson.otp.erlang.OtpErlangInt;
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.common.OtpErlangHelper;
import com.refactorerl.ui.communication.MessageParseHelper;
import com.refactorerl.ui.communication.ReferlProxy;
import com.refactorerl.ui.communication.exceptions.AbortRequestException;
import com.refactorerl.ui.logic.AbstractRequest;


class InternalQueryRequest extends AbstractRequest<OtpErlangList> {

	private String filePath;
	private Integer position;
	private String query;
	private OtpErlangTuple request;

	protected InternalQueryRequest(String filePath, Integer position, String query, ReferlProxy proxy, Logger logger) {
		super(proxy, logger);
		this.filePath = filePath;
		this.position = position;
		this.query = query;
		
		OtpErlangTuple displayOpt = createDisplayOpt();
		OtpErlangTuple startOpt = createStartOpt();
		OtpErlangTuple queryStr = createQueryStr();

		request = new OtpErlangTuple(new OtpErlangObject[] { new OtpErlangAtom("transform"), //$NON-NLS-1$
				new OtpErlangAtom("semantic_query"), //$NON-NLS-1$
				new OtpErlangList(new OtpErlangObject[] { displayOpt, startOpt, queryStr }) });
	}

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

	@Override
	protected OtpErlangList doProcessReply(OtpErlangObject m) throws AbortRequestException {

		OtpErlangObject body = MessageParseHelper.getBody(m); // {ok, {...}}
		OtpErlangObject inner = OtpErlangHelper.nth(body, 1); // {abort,
																	// {Error,
																	// Message}
																	// | {any(),
																	// ...}}
		if (OtpErlangHelper.nthEqualsAtom(inner, 0, "abort")) { //$NON-NLS-1$
			OtpErlangObject errorMessage = OtpErlangHelper.nth(OtpErlangHelper.nth(inner, 1), 1);
			throw new AbortRequestException(OtpErlangHelper.toUnquotedString(errorMessage));
		}

		// old code

		try {
			OtpErlangTuple msgBody0 = (OtpErlangTuple) MessageParseHelper.getBody(m);
			// {ok, {result, [{result, [...]}, ...]}}
			// [{group_by, {nopos, Origin}, list, [...]}, ...]
			// [{{FilePath, startPos, endPos}, Result}, ...]

			// A reply can be a success(ok) or a fail(error)
			if (msgBody0.arity() > 1 && OtpErlangHelper.nthEqualsAtom(msgBody0, 0, "ok")) { //$NON-NLS-1$

				OtpErlangTuple msgBody1 = OtpErlangHelper.nth(msgBody0, 1);

				if (!(msgBody1.arity() == 2 && OtpErlangHelper.nthEqualsAtom(msgBody1, 0, "result"))) //$NON-NLS-1$
					return null; 

				OtpErlangList resultList0 = OtpErlangHelper.nth(msgBody1, 1);

				for (OtpErlangObject o : resultList0) {
					if (OtpErlangHelper.nthEqualsAtom(o, 0, "result")) { //$NON-NLS-1$

						final OtpErlangList results = OtpErlangHelper.nth(o, 1);
						return results;
					} else if (OtpErlangHelper.nthEqualsAtom(o, 0, "saved")) //$NON-NLS-1$
						System.out.println(Messages.InternalQueryRequest_0); // FIXME
					else if (OtpErlangHelper.nthEqualsAtom(o, 0, "renamed")) //$NON-NLS-1$
						System.out.println(Messages.InternalQueryRequest_9); // FIXME
				}

			} else if (msgBody0.arity() > 1
					&& (OtpErlangHelper.nthEqualsAtom(msgBody0, 0, "error") || OtpErlangHelper.nthEqualsAtom(msgBody0, //$NON-NLS-1$
							0, "abort"))) { //$NON-NLS-1$
				System.out.println(Messages.InternalQueryRequest_12); // FIXME
			}
		} catch (ClassCastException e) {
			System.out.println(Messages.InternalQueryRequest_13); // FIXME
		}

		return null;
	}

	private OtpErlangTuple createDisplayOpt() {
		return new OtpErlangTuple(new OtpErlangObject[] {
				new OtpErlangAtom("display_opt"), //$NON-NLS-1$
				OtpErlangHelper.createList(
						OtpErlangHelper.createTuple(new OtpErlangAtom("positions"), new OtpErlangAtom("scalar")), //$NON-NLS-1$ //$NON-NLS-2$
						OtpErlangHelper.createTuple(new OtpErlangAtom("output"), new OtpErlangAtom("other"))) }); //$NON-NLS-1$ //$NON-NLS-2$
	}

	private OtpErlangTuple createQueryStr() {
		return OtpErlangHelper.createTuple(new OtpErlangAtom("querystr"), new OtpErlangString(query)); //$NON-NLS-1$
	}

	private OtpErlangTuple createStartOpt() {

		OtpErlangList opts;
		if (filePath == null)
			opts = new OtpErlangList();
		else {
			OtpErlangTuple fileTuple = OtpErlangHelper.createTuple(new OtpErlangAtom("file"), new OtpErlangString( //$NON-NLS-1$
					filePath));
			if (position == null)
				opts = OtpErlangHelper.createList(fileTuple);
			else {
				OtpErlangTuple positionTuple = OtpErlangHelper.createTuple(new OtpErlangAtom("position"), //$NON-NLS-1$
						new OtpErlangInt(position));
				opts = OtpErlangHelper.createList(fileTuple, positionTuple);
			}
		}
		return new OtpErlangTuple(new OtpErlangObject[] { new OtpErlangAtom("start_opt"), opts }); //$NON-NLS-1$
	}

	@Override
	public String toString() {
		String str = query;
		if (filePath != null)
			str += "/" + filePath.substring(filePath.lastIndexOf('/') + 1); //$NON-NLS-1$
		;
		if (position != null)
			str += "/" + position; //$NON-NLS-1$
		return str;
	}

}
