package service;
import api.v1.StandardAccount;
import exceptions.PoseidonException;
import mapper.StandardAccountMapper;
import models.StandardAccountModel;
import play.mvc.Http;
import java.util.Date;
import java.util.List;
public class StandardAccountService extends PoseidonService {
public StandardAccountService(String username) {
super(username);
}
public List<StandardAccountModel> findAll() {
return StandardAccountModel.find.all();
}
public StandardAccountModel getById(long id) {
return StandardAccountModel.find.byId(id);
}
public StandardAccountModel findByName(String name) {
return StandardAccountModel.find.where().ieq("name", name).findUnique();
}
public StandardAccountModel findByAccount(String account) {
return StandardAccountModel.find.where().ieq("account", account).findUnique();
}
public StandardAccountModel createOrUpdate(StandardAccount apiStandardAccount) {
StandardAccountModel mStandardAccount = null;
if ((apiStandardAccount.id != null) && (apiStandardAccount.id > 0)) {
mStandardAccount = updateExisting(apiStandardAccount);
} else {
StandardAccountModel p = StandardAccountModel.findByName(apiStandardAccount.name);
if (p != null && p.deleted == null) {
throw new PoseidonException(Http.Status.BAD_REQUEST, "Produktets navn er ikke unikt");
}
if (p != null) { // exists, but deleted, resurrect it
mStandardAccount = p;
mStandardAccount.deleted = null;
mStandardAccount.deletedBy = null;
} else {
mStandardAccount = new StandardAccountMapper().mapToModel(apiStandardAccount,mStandardAccount);
}
mStandardAccount.created = PoseidonService.getNow().toDate();
mStandardAccount.createdBy = getUser();
}
mStandardAccount.save();
return mStandardAccount;
}
private StandardAccountModel updateExisting(StandardAccount aStandardAccount) {
StandardAccountModel mStandardAccount = getById(aStandardAccount.id);
mStandardAccount.name = aStandardAccount.name;
mStandardAccount.account= aStandardAccount.account;
mStandardAccount.updated = PoseidonService.getNow().toDate();
mStandardAccount.updatedBy = getUser();
return mStandardAccount;
}
public StandardAccountModel deleteStandardAccount(Long id) {
StandardAccountModel standardAccountModel = getById(id);
if (standardAccountModel != null) {
standardAccountModel.deleted = PoseidonService.getNow().toDate();
standardAccountModel.deletedBy = getUser();
standardAccountModel.save();
}
return standardAccountModel;
}
}