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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

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

public class CloneIdentifierlRequest extends AbstractRequest<CloneData> {

	private OtpErlangTuple request;

	public CloneIdentifierlRequest(String algorithmKey, List<AlgorithmData> params, ReferlProxy proxy, Logger logger) {
		super(proxy, logger);

		for (AlgorithmData aData : params) {
			if (aData.getValue() == null) {
				throw new IllegalArgumentException(Messages.CloneIdentifierlRequest_0);
			}
		}

		Map<String, OtpErlangObject> otpParams = new HashMap<>();

		otpParams.put("algorithm", new OtpErlangAtom(algorithmKey)); //$NON-NLS-1$
		otpParams.put("format", new OtpErlangAtom("file_and_loc")); //$NON-NLS-1$ //$NON-NLS-2$
		otpParams.put("postype", new OtpErlangAtom("scalar")); //$NON-NLS-1$ //$NON-NLS-2$

		for (AlgorithmData aData : params) {
			OtpErlangObject o = null;
			switch (aData.type) {
			case ATOM:
				o = new OtpErlangAtom(trimmedString(aData.getValue()));
				break;
			case ATOMS:
				List<String> ls = (List<String>) aData.getValue();
				OtpErlangAtom[] otpLs = new OtpErlangAtom[ls.size()];
				int i = 0;
				for (String s : ls) {
					otpLs[i] = new OtpErlangAtom(trimmedString(s));
					++i;
				}
				o = OtpErlangHelper.createList(otpLs);

				break;
			case BOOL:
				o = new OtpErlangBoolean((Boolean) aData.getValue());
				break;
			case ENUM:
				switch (aData.enumType) {
				case ATOM:
					o = new OtpErlangAtom(trimmedString(aData.getValue()));
					break;
				case STRING:
					o = new OtpErlangString(trimmedString(aData.getValue()));
					break;
				}
				break;
			case FLOAT:
				o = new OtpErlangDouble((Double) aData.getValue());
				break;
			case INT:
				o = new OtpErlangInt((Integer) aData.getValue());
				break;
			}

			otpParams.put(aData.key, o);
		}

		if (otpParams.get("name") != null && ((OtpErlangAtom) otpParams.get("name")).atomValue().isEmpty()) { //$NON-NLS-1$ //$NON-NLS-2$
			otpParams.remove("name"); //$NON-NLS-1$

		}

		request = new OtpErlangTuple(new OtpErlangObject[] { new OtpErlangAtom("clone_identifierl"), //$NON-NLS-1$
				OtpErlangHelper.createPropList(otpParams) });

	}

	@Override
	public boolean isModifier() {
		return true;
	}
	
	@Override
	protected OtpErlangObject doGetRequest() {

		return request;
	}

	@Override
	protected CloneData doProcessReply(OtpErlangObject m) throws RequestException {

		OtpErlangList cloneData = (OtpErlangList) OtpErlangHelper.nth(MessageParseHelper.getBody(m), 1);

		Map<String, OtpErlangObject> propList = OtpErlangHelper.translatePropList(cloneData);

		String cloneName = OtpErlangHelper.toUnquotedString(propList.get("clone_name")); //$NON-NLS-1$
		String outputPath = OtpErlangHelper.toUnquotedString(propList.get("output_file_path")); //$NON-NLS-1$
		List<GroupData> groups = new ArrayList<>();
		final OtpErlangList otpGroups = (OtpErlangList) propList.get("detected_clones"); //$NON-NLS-1$
		for (OtpErlangObject o : otpGroups) {
			groups.add(parseDup(o, cloneName));
		}

		return new CloneData(groups, cloneName, outputPath);
	}

	private GroupData parseDup(OtpErlangObject o, String parentName) {
		
		final int groupId = Integer.parseInt(OtpErlangHelper.toUnquotedString(OtpErlangHelper.nth(o, 0)));
		final OtpErlangList otpMembers = (OtpErlangList) OtpErlangHelper.nth(o, 1);
		final int memberCount = otpMembers.arity();
		final FilePosition[] members = new FilePosition[memberCount];
		for (int i = 0; i < memberCount; i++) {
			final OtpErlangList otpMem = (OtpErlangList) OtpErlangHelper.nth(otpMembers, i);
			final Map<String, OtpErlangObject> propMem = OtpErlangHelper.translatePropList(otpMem);
			
			final String filePath =  OtpErlangHelper.toUnquotedString(propMem.get("filepath")); //$NON-NLS-1$
			final int startPos = Integer.parseInt(OtpErlangHelper.toUnquotedString(propMem.get("startpos"))); //$NON-NLS-1$
			final int endPos = Integer.parseInt(OtpErlangHelper.toUnquotedString(propMem.get("endpos"))); //$NON-NLS-1$
			
			FilePosition mem = new FilePosition(filePath, startPos, endPos);
			members[i] = mem;			
		}
		
		return new GroupData(groupId, members, parentName);
	}

	private String trimmedString(Object v) {
		return ((String) v).trim();
	}

}
