package com.perforce.spark.depot;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.perforce.p4java.core.IDepot;
import com.perforce.p4java.core.IDepot.DepotType;
import com.perforce.p4java.exception.P4JavaException;
import com.perforce.p4java.impl.generic.core.Depot;
import com.perforce.p4java.server.IOptionsServer;
import com.perforce.spark.artifact.ArtifactType;
import com.perforce.spark.repository.AbstractRepoAdapter;
import com.perforce.spark.repository.RepoInterface;
import com.perforce.spark.site.SiteType;
import com.perforce.spark.store.PerforceStore;
public class DepotModel {
private RepoInterface repo;
public DepotModel(RepoInterface repo) {
this.repo = repo;
}
public DepotModel(IDepot depot) {
repo = stringToRepo(depot.getDescription());
if (repo == null) {
repo = new PerforceStore(depot);
}
}
private RepoInterface stringToRepo(String description) {
RepoInterface repo = null;
for (String line : description.split("\n")) {
if (line.startsWith("Json:")) {
String values[] = line.split("Json:");
String json = values[1].trim();
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(RepoInterface.class,
new AbstractRepoAdapter());
Gson gson = gsonBuilder.create();
repo = gson.fromJson(json, RepoInterface.class);
}
}
return repo;
}
private String repoToString(RepoInterface repo) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
String json = gson.toJson(repo);
return "Json:" + json;
}
public String getName() {
return repo.getName();
}
public ArtifactType getType() {
return repo.getArtifactType();
}
public SiteType getSite() {
return repo.getSiteType();
}
public String getTitle() {
return repo.getTitle();
}
public String getDescription() {
return repo.getDescription();
}
public String getLink() {
return "/browse/" + getName();
}
public String getPath() {
return "//" + getName();
}
public String getIcon() {
String type = repo.getArtifactType().getId();
return "/images/" + type + "-64x80.png";
}
public RepoInterface getRepo() {
return repo;
}
public void create(IOptionsServer p4) throws P4JavaException {
if (getName() == null) {
throw new P4JavaException("Invalid depot configuration.");
}
IDepot depot = p4.getDepot(getName());
Depot implDepot = new Depot();
implDepot.setName(getName());
implDepot.setOwnerName(depot.getOwnerName());
implDepot.setDescription(repoToString(repo));
implDepot.setDepotType(DepotType.LOCAL);
implDepot.setMap(depot.getMap());
p4.createDepot(implDepot);
}
public String toString() {
return repo.toString();
}
}