# -*- encoding : utf-8 -*-

class Admin::StockBlocksController < ApplicationController
  layout "admin"
  before_action :auth_admin

  before_action :admin_space
  
  def admin_space
    @admin_space = "default"
  end
  
  def index
    @stock_blocks = StockBlock.order(:name).all

  end

  def show
    @stock_block = StockBlock.find(params[:id])

  end

  def new
    @stock_block = StockBlock.new(:stockable_type => params[:stockable_type],:stockable_id => params[:stockable_id])
    
  
    @stockable = @stock_block.stockable
    
    if @stockable and (defined? @stockable.movement_type) and @stockable.movement_type == "cred"
      @stock_block.movement_type = "deb"
    else
      @stock_block.movement_type = "cred"
    end
      
    if @stockable and (defined? @stockable.accounting)
      @stock_block.accounting = @stockable.accounting
    end
    
    
    if @stockable and (defined? @stockable.price_line_block) and @stockable.price_line_block and @stockable.price_line_block.movement_type == "cred"
      @stock_block.movement_type = "deb"
    else
      @stock_block.movement_type = "cred"
    end
    
    if @stockable and (defined? @stockable.price_line_block) and @stockable.price_line_block
      @stock_block.accounting = @stockable.price_line_block.accounting
    end
    
    
    
    
    if @stockable and @stockable.price_line_block
      @stockable.price_line_block.price_lines.each do |pl|
        
        if pl.p_product_ref and pl.p_product_ref.stocked
          qte = pl.qte.to_f - @stockable.stock_lines.where(:p_product_ref_id => pl.p_product_ref_id).sum(:qte)
          @stock_block.stock_lines << StockLine.new(:p_product_ref_id => pl.p_product_ref_id , :qte => qte, :ct_price_u_ht => pl.price_u_ht)
        end
      
      end
      
    end
  
  end

  def edit
    @stock_block = StockBlock.find(params[:id])
    
  end

  def create
    @stock_block = StockBlock.new(params.require(:stock_block).permit!)
    @stock_block.admin = current_admin
    if @stock_block.save
      if @stock_block.stockable
        redirect_to [:admin, @stock_block.stockable]
      end
    else
      render action: "new"
 
    end

  end


  def update
    @stock_block = StockBlock.find(params[:id])


    if @stock_block.update_attributes(params.require(:stock_block).permit!)
      
    else
     render action: "edit" 
      
    end
      
  end


  def destroy
    @stock_block = StockBlock.find(params[:id])
    @stock_block.destroy
    
  end
end
