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

class Admin::PShipToursController < ApplicationController
  layout "admin"
  before_filter :auth_admin

  before_filter :admin_space
  
  def to_ship
    @p_ship_tour = PShipTour.find(params[:id])
    @p_ship_tour.to_ship
    redirect_to :back
  end
  
  def ship_return
    @p_ship_tour = PShipTour.find(params[:id])
    
    
    @p_ship_tour.p_ship_tour_trucks.each do |p_ship_tour_truck|
      
      i = 0.0
      
      if p_ship_tour_truck.p_volucompteurs.count == 0
        last_volucompteur = PVolucompteur.where(:p_truck_id => p_ship_tour_truck.p_truck_id).order("end_vol DESC").first
      
        i = last_volucompteur.end_vol if last_volucompteur
      
        p_ship_tour_truck.p_volucompteurs.build(:start_vol => i, :p_truck_id => p_ship_tour_truck.p_truck_id) if !p_ship_tour_truck.remorque
    
      end
      
    end
    
  end
  
  def ship_return_save
    @p_ship_tour = PShipTour.find(params[:id])
    #@p_ship_tour.reset_validation
    if @p_ship_tour.update_attributes(params.require(:p_ship_tour).permit!)
      @p_ship_tour.p_ship_tour_trucks.each do |p_ship_tour_truck|
        p_ship_tour_truck.p_volucompteurs.each do |p_volucompteur|
          p_volucompteur.check_delta = true
          p_volucompteur.valid?
        
        end
      end
      #render :inline => @p_ship_tour.valid?
      if @p_ship_tour.save
      
        @p_ship_tour.done_return
      
        redirect_to admin_p_ship_tour_path(@p_ship_tour)
      else
        render action: "ship_return"
      end

    else
      render action: "ship_return"
 
    end
    
  end
  
  
  def admin_space
    @admin_space = "tournees"
  end
  
  def index
    @p_ship_tours = PShipTour.order("start_at DESC").all

   
  end

  def show
    @p_ship_tour = PShipTour.find(params[:id])

  end

  def new
    
    
		@p_ship_tour = PShipTour.new(:start_at => Time.now)
    
    PTruck.all.each do |p_truck|
      p_ship_tour_truck = PShipTourTruck.new(:p_truck => p_truck)
      p_truck.p_truck_spaces.each do |p_truck_space|
        p_ship_space = PShipSpace.new(:p_truck_space => p_truck_space)
        p_ship_tour_truck.p_ship_spaces << p_ship_space
      end
      @p_ship_tour.p_ship_tour_trucks << p_ship_tour_truck
      
    end
    

  end

 

  def edit
  
    
    @p_ship_tour = PShipTour.find(params[:id])
  end

  def create
    @p_ship_tour = PShipTour.new(params.require(:p_ship_tour).permit!)


    if @p_ship_tour.save
     @p_ship_tours = PShipTour.order("start_at DESC").all
      
    else
      render action: "new"
 
    end

  end


  def update
    @p_ship_tour = PShipTour.find(params[:id])


    if @p_ship_tour.update_attributes(params.require(:p_ship_tour).permit!)
      
       @p_ship_tours = PShipTour.order("start_at DESC").all
    else
     render action: "edit" 
      
    end
      
  end


  def destroy
    @p_ship_tour = PShipTour.find(params[:id])
    @p_ship_tour.destroy
    
    
  end
end
