# -*- encoding : utf-8 -*-
class CelTable < ActiveRecord::Base
  belongs_to :table_row
  #belongs_to :table_content possible
  
  has_one :block, :as => :blockable, :dependent => :destroy
  
  attr_accessor :skip_before_update




  before_create do
    if !position
      self.position = 1
    end
    if position
      CelTable.where(["position >= ? and table_row_id = ?",self.position,self.table_row_id]).each do |cel_table|
        cel_table.position = cel_table.position + 1
        cel_table.skip_before_update = true
        cel_table.save!
      end
    end
    
    
    
  end
  
  after_create do 
    block = Block.create()
  
    self.block = block
  end

  before_update do
    if !skip_before_update
      if self.position_changed?
        #si la position est plus grande que l'ancienne
        if self.changes['position'][1] > self.changes['position'][0]
          CelTable.where(["position > ? and position <= ? and table_row_id = ?",self.changes['position'][0],self.changes['position'][1],self.table_row_id]).each do |cel_table|
            cel_table.position = cel_table.position - 1
            cel_table.skip_before_update = true
            cel_table.save!
          end
        end
        #si la position est plus petite que l'ancienne.  
        if self.changes['position'][1] < self.changes['position'][0]
          CelTable.where(["position >= ? and position < ? and table_row_id = ?",self.changes['position'][1],self.changes['position'][0],self.table_row_id]).each do |cel_table|
            cel_table.position = cel_table.position + 1
            cel_table.skip_before_update = true
            cel_table.save!
          end  
        end 
      end
    end
  end

  before_destroy do
    CelTable.where(["position > ? and table_row_id = ?",self.position,self.table_row_id]).each do |cel_table|
      cel_table.position = cel_table.position - 1
      cel_table.skip_before_update = true
      cel_table.save!
    end

  end
  
  def dup
    @new = CelTable.new(self.attributes)
    @new.id = nil
    @new.table_row_id = nil
    @new.save
    
    @new.block.destroy
  
      
      new_b = self.block.dup
      
    

      new_b.save
      @new.block = new_b
      @new.save
    
    @new
    
  end
  
  
  
end
