package org.jenkinsci.plugins.p4.scm;

import jenkins.scm.api.SCMHead;
import jenkins.scm.api.mixin.ChangeRequestSCMHead;
import org.jenkinsci.plugins.p4.PerforceScm;
import org.jenkinsci.plugins.p4.changes.P4Ref;
import org.jenkinsci.plugins.p4.review.P4Review;
import org.jenkinsci.plugins.p4.tasks.CheckoutStatus;

public class P4ChangeRequestSCMHead extends P4SCMHead implements ChangeRequestSCMHead {

	private static final long serialVersionUID = 1L;

	private final SCMHead target;
	private final String review;

	P4ChangeRequestSCMHead(String name, String review, P4Path path, SCMHead target) {
		super(name, path);
		this.target = target;
		this.review = review;
	}

	@Override
	public String getId() {
		return getName();
	}

	public String getReview() {
		return review;
	}

	/**
	 * Branch to which this change would be merged or applied if it were accepted.
	 *
	 * @return a “target” or “base” branch
	 */
	@Override
	public SCMHead getTarget() {
		return target;
	}

	@Override
	public PerforceScm getScm(AbstractP4ScmSource source, P4Path path, P4Ref revision) {
		PerforceScm scm = new PerforceScm(source, path, revision);
		P4Review review = new P4Review(getName(), CheckoutStatus.SHELVED);
		scm.setReview(review);
		return scm;
	}
}

@@ -106,23 +106,135 @@
 eRequest
-SCMHead
+CheckoutStrategy;%0Aimport jenkins.scm.api.mixin.ChangeRequestSCMHead;%0Aimport jenkins.scm.api.mixin.ChangeRequestSCMHead2
 ;%0Aimport
@@ -508,16 +508,39 @@
 tSCMHead
+, ChangeRequestSCMHead2
  %7B%0A%0A%09pri
@@ -1378,11 +1378,238 @@
  scm;%0A%09%7D
+%0A%0A%09@Override%0A%09public ChangeRequestCheckoutStrategy getCheckoutStrategy() %7B%0A%09%09return ChangeRequestCheckoutStrategy.MERGE;%0A%09%7D%0A%0A%09@Override%0A%09public String getOriginName() %7B%0A%09%09return ((P4SCMHead) getTarget()).getPath().getPath();%0A%09%7D
 %0A%7D%0A

implement ChangeRequestSCMHead2 interface for P4ChangeRequestSCMHead so the CHANGE_BRANCH environment variable has a valid P4 depot path for the swarm review target