package com.dak.duty.service;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dak.duty.model.Duty;
import com.dak.duty.repository.DutyRepository;

@Service
@Transactional
public class DutyService {

   @Autowired
   DutyRepository dutyRepos;

   public Duty saveOrUpdateDuty(Duty duty){

      /**
       * 1) Decrement all sort orders [>] old sort order (if this is an update, not a new item)
       * 2) Increment all sort orders [>=] new / updated duty sort order IF this isn't an inactive duty
       * 3) Persist duty w/ new sort order
       */
      if(duty.getId() > 0){ // if this is an update, not a new entity
         final Duty dutyBeforeChanges = dutyRepos.findOne(duty.getId());

         if(!duty.getActive() && dutyBeforeChanges.getActive()){ // if we're deactivating this duty ...
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
            
            duty.setName(duty.getName() + " (deleted @ " + sdf.format(new Date()) + ")"); // change name to show soft delete and to prevent key errors if another with same name added later
            dutyRepos.decrementSortOrderAboveAndIncludingExcludingDutyId(dutyBeforeChanges.getSortOrder(), duty.getId());
         }
         if(duty.getActive() && !duty.getSortOrder().equals(dutyBeforeChanges.getSortOrder())){
            dutyRepos.decrementSortOrderAboveExcludingDutyId(dutyBeforeChanges.getSortOrder(), duty.getId());
            dutyRepos.incrementSortOrderAboveAndIncludingExcludingDutyId(duty.getSortOrder(), duty.getId());
         }
      } else {
         dutyRepos.incrementSortOrderAboveAndIncluding(duty.getSortOrder());
      }

      return dutyRepos.save(duty);
   }
}

@@ -497,16 +497,195 @@
        *
+ If this is a soft delete:%0D%0A       *  1) Update name accordingly, decrement sort order %5B%3E=%5D current duty.sortOrder%0D%0A       * %0D%0A       * Otherwise (update or a new duty)%0D%0A       * 
  1) Decr
@@ -773,16 +773,17 @@
        *
+ 
  2) Incr
@@ -879,16 +879,17 @@
        *
+ 
  3) Pers
@@ -1070,24 +1070,24 @@
 etId());%0D%0A%0D%0A
-
          if(
@@ -1164,16 +1164,32 @@
 ivating 
+/ soft deleting 
 this dut

clarify comments for DutyService