/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.app.plugin.core.function.editor;

import ghidra.program.model.address.Address;
import ghidra.program.model.lang.Register;
import ghidra.program.model.listing.Program;
import ghidra.program.model.pcode.Varnode;

class VarnodeInfo {

	private VarnodeType type;
	private Address address;
	private Integer size;
	private Register register;

	private final Program program;

	VarnodeInfo(Program program, VarnodeType type) {
		this.program = program;
		this.type = type;
	}

	VarnodeInfo(Program program, Varnode varnode) {
		this.program = program;
		setVarnode(varnode);
	}

	public VarnodeType getType() {
		return type;
	}

	public Address getAddress() {
		return address;
	}

	public Integer getSize() {
		return size;
	}

	public void setVarnodeType(VarnodeType type) {
		this.type = type;
		address = null;
		register = null;
		if (type == VarnodeType.Register) {
			size = null;
		}
	}

	public void setVarnode(Address address, Integer size) {
		this.address = address;
		this.size = size;
		register = getRegister(program, address, size);
		if (address == null) {
			return;
		}
		if (address.isRegisterAddress() || register != null) {
			type = VarnodeType.Register;
		}
		else if (address.isStackAddress()) {
			type = VarnodeType.Stack;
		}
		else if (address.isMemoryAddress()) {
			type = VarnodeType.Memory;
		}
		else {
			throw new IllegalArgumentException("Illegal varnode address type");
		}
	}

	public void setVarnode(Varnode varnode) {
		setVarnode(varnode.getAddress(), varnode.getSize());
	}

	public Register getRegister() {
		return register;
	}

	public static Register getRegister(Program program, Address address, Integer size) {
		if (address == null) {
			return null;
		}
		if (!address.isRegisterAddress() && !address.getAddressSpace().hasMappedRegisters()) {
			return null;
		}
		if (size == null) {
			return program.getRegister(address);
		}
		Register register = program.getRegister(address, size);
		if (register == null) {
			register = program.getRegister(address);
		}
		return register;

	}

}
