public TemplateProfile prepareDelete(DeleteTemplateCmd cmd) {
    Long templateId = cmd.getId();
    Long userId = UserContext.current().getCallerUserId();
    Account account = UserContext.current().getCaller();
    Long zoneId = cmd.getZoneId();

    VMTemplateVO template = _tmpltDao.findById(templateId.longValue());
    if (template == null) {
      throw new InvalidParameterValueException("unable to find template with id " + templateId);
    }

    userId =
        accountAndUserValidation(account, userId, null, template, "Unable to delete template ");

    UserVO user = _userDao.findById(userId);
    if (user == null) {
      throw new InvalidParameterValueException("Please specify a valid user.");
    }

    if (template.getFormat() == ImageFormat.ISO) {
      throw new InvalidParameterValueException("Please specify a valid template.");
    }

    return new TemplateProfile(userId, template, zoneId);
  }
  @DB
  public void handleDownloadEvent(HostVO host, VMTemplateVO template, Status dnldStatus) {
    if ((dnldStatus == VMTemplateStorageResourceAssoc.Status.DOWNLOADED)
        || (dnldStatus == Status.ABANDONED)) {
      VMTemplateHostVO vmTemplateHost = new VMTemplateHostVO(host.getId(), template.getId());
      synchronized (_listenerMap) {
        _listenerMap.remove(vmTemplateHost);
      }
    }

    VMTemplateHostVO vmTemplateHost =
        _vmTemplateHostDao.findByHostTemplate(host.getId(), template.getId());

    Transaction txn = Transaction.currentTxn();
    txn.start();

    if (dnldStatus == Status.DOWNLOADED) {
      long size = -1;
      if (vmTemplateHost != null) {
        size = vmTemplateHost.getPhysicalSize();
        template.setSize(size);
        this._templateDao.update(template.getId(), template);
      } else {
        s_logger.warn("Failed to get size for template" + template.getName());
      }
      String eventType = EventTypes.EVENT_TEMPLATE_CREATE;
      if ((template.getFormat()).equals(ImageFormat.ISO)) {
        eventType = EventTypes.EVENT_ISO_CREATE;
      }
      if (template.getAccountId() != Account.ACCOUNT_ID_SYSTEM) {
        UsageEventUtils.publishUsageEvent(
            eventType,
            template.getAccountId(),
            host.getDataCenterId(),
            template.getId(),
            template.getName(),
            null,
            template.getSourceTemplateId(),
            size,
            template.getClass().getName(),
            template.getUuid());
      }
    }
    txn.commit();
  }
  @Override
  @DB
  public boolean remove(Long id) {
    Transaction txn = Transaction.currentTxn();
    txn.start();
    VMTemplateVO template = createForUpdate();
    template.setRemoved(new Date());

    VMTemplateVO vo = findById(id);
    if (vo != null) {
      if (vo.getFormat() == ImageFormat.ISO) {
        _tagsDao.removeByIdAndType(id, TaggedResourceType.ISO);
      } else {
        _tagsDao.removeByIdAndType(id, TaggedResourceType.Template);
      }
    }

    boolean result = update(id, template);
    txn.commit();
    return result;
  }
  @Override
  @DB
  public boolean delete(TemplateProfile profile) {
    boolean success = true;

    VMTemplateVO template = profile.getTemplate();
    Long zoneId = profile.getZoneId();
    Long templateId = template.getId();

    String zoneName;
    List<HostVO> secondaryStorageHosts;
    if (!template.isCrossZones() && zoneId != null) {
      DataCenterVO zone = _dcDao.findById(zoneId);
      zoneName = zone.getName();
      secondaryStorageHosts = _ssvmMgr.listSecondaryStorageHostsInOneZone(zoneId);
    } else {
      zoneName = "(all zones)";
      secondaryStorageHosts = _ssvmMgr.listSecondaryStorageHostsInAllZones();
    }

    s_logger.debug(
        "Attempting to mark template host refs for template: "
            + template.getName()
            + " as destroyed in zone: "
            + zoneName);

    // Make sure the template is downloaded to all the necessary secondary storage hosts
    for (HostVO secondaryStorageHost : secondaryStorageHosts) {
      long hostId = secondaryStorageHost.getId();
      List<VMTemplateHostVO> templateHostVOs = _tmpltHostDao.listByHostTemplate(hostId, templateId);
      for (VMTemplateHostVO templateHostVO : templateHostVOs) {
        if (templateHostVO.getDownloadState() == Status.DOWNLOAD_IN_PROGRESS) {
          String errorMsg = "Please specify a template that is not currently being downloaded.";
          s_logger.debug(
              "Template: "
                  + template.getName()
                  + " is currently being downloaded to secondary storage host: "
                  + secondaryStorageHost.getName()
                  + "; cant' delete it.");
          throw new CloudRuntimeException(errorMsg);
        }
      }
    }

    Account account = _accountDao.findByIdIncludingRemoved(template.getAccountId());
    String eventType = "";

    if (template.getFormat().equals(ImageFormat.ISO)) {
      eventType = EventTypes.EVENT_ISO_DELETE;
    } else {
      eventType = EventTypes.EVENT_TEMPLATE_DELETE;
    }

    // Iterate through all necessary secondary storage hosts and mark the template on each host as
    // destroyed
    for (HostVO secondaryStorageHost : secondaryStorageHosts) {
      long hostId = secondaryStorageHost.getId();
      long sZoneId = secondaryStorageHost.getDataCenterId();
      List<VMTemplateHostVO> templateHostVOs = _tmpltHostDao.listByHostTemplate(hostId, templateId);
      for (VMTemplateHostVO templateHostVO : templateHostVOs) {
        VMTemplateHostVO lock = _tmpltHostDao.acquireInLockTable(templateHostVO.getId());
        try {
          if (lock == null) {
            s_logger.debug(
                "Failed to acquire lock when deleting templateHostVO with ID: "
                    + templateHostVO.getId());
            success = false;
            break;
          }
          UsageEventVO usageEvent =
              new UsageEventVO(eventType, account.getId(), sZoneId, templateId, null);
          _usageEventDao.persist(usageEvent);
          templateHostVO.setDestroyed(true);
          _tmpltHostDao.update(templateHostVO.getId(), templateHostVO);
          String installPath = templateHostVO.getInstallPath();
          if (installPath != null) {
            Answer answer =
                _agentMgr.sendToSecStorage(
                    secondaryStorageHost,
                    new DeleteTemplateCommand(secondaryStorageHost.getStorageUrl(), installPath));

            if (answer == null || !answer.getResult()) {
              s_logger.debug(
                  "Failed to delete "
                      + templateHostVO
                      + " due to "
                      + ((answer == null) ? "answer is null" : answer.getDetails()));
            } else {
              _tmpltHostDao.remove(templateHostVO.getId());
              s_logger.debug("Deleted template at: " + installPath);
            }
          } else {
            _tmpltHostDao.remove(templateHostVO.getId());
          }
          VMTemplateZoneVO templateZone = _tmpltZoneDao.findByZoneTemplate(sZoneId, templateId);

          if (templateZone != null) {
            _tmpltZoneDao.remove(templateZone.getId());
          }
        } finally {
          if (lock != null) {
            _tmpltHostDao.releaseFromLockTable(lock.getId());
          }
        }
      }

      if (!success) {
        break;
      }
    }

    s_logger.debug(
        "Successfully marked template host refs for template: "
            + template.getName()
            + " as destroyed in zone: "
            + zoneName);

    // If there are no more non-destroyed template host entries for this template, delete it
    if (success && (_tmpltHostDao.listByTemplateId(templateId).size() == 0)) {
      long accountId = template.getAccountId();

      VMTemplateVO lock = _tmpltDao.acquireInLockTable(templateId);

      try {
        if (lock == null) {
          s_logger.debug("Failed to acquire lock when deleting template with ID: " + templateId);
          success = false;
        } else if (_tmpltDao.remove(templateId)) {
          // Decrement the number of templates
          _resourceLimitMgr.decrementResourceCount(accountId, ResourceType.template);
        }

      } finally {
        if (lock != null) {
          _tmpltDao.releaseFromLockTable(lock.getId());
        }
      }

      s_logger.debug(
          "Removed template: "
              + template.getName()
              + " because all of its template host refs were marked as destroyed.");
    }

    return success;
  }