require 'pixways'
class Uploads::PhotosController < ApplicationController

  layout "simple_provider"

  before_filter :login_required
  before_filter :load_cached_search_params, only: [:index, :updt_to_csv]

  def index
    if params[:per_page]
      per_page = params[:per_page]
    elsif @current_params[:per_page]
      per_page = @current_params[:per_page]
    else
      per_page = 60
    end

    page = 1
    page = params["page"].to_i if params["page"] && params["page"].to_i > 0

    unless @current_params[:search_since]
      if cookies[:stats_since].present?
        @current_params[:search_since] = cookies[:stats_since]
      else
        @current_params[:search_since] = "1_month"
      end
    end
    cookies[:stats_since] = @current_params[:search_since]

    l_prov = []
    if Server.itself?(VINGTMINUTES_SERVER_NAME)
      @providers = Provider.where('string_key like ? and string_key != ?',"20min_%","20min_Afp").order(:name)
      @providers.each{|p| l_prov << p.id}
    else
      session[:provhd].each_index{|i| l_prov << i if session[:provhd][i] == 1}
      if l_prov.blank?
        session[:provbd].each_index{|i| l_prov << i if session[:provbd][i] == 1}
      end
      @providers = Provider.where(id: l_prov).order(:name)
    end

    sort = @current_params["sort"] ? @current_params["sort"] : 'reception_date desc'

    with = {}
    with[:content_error]  = 0
    providers_list = @current_params[:providers].blank? ? l_prov : @current_params[:providers].keys.collect!{|e| e.to_i}
    with[:provider_id] = providers_list
    with[:updated_at] = Pixways::SearchesHelper.dates_to_range('',params[:search_time]) if params[:search_time]
    with[:reception_date] = Image.since_conditions(@current_params[:search_since]) if params[:search_since] && params[:search_since] != 'all'
    with[:reception_date] = Pixways::SearchesHelper.dates_to_range(params[:reception_date_begin], params[:reception_date_end]) unless (params[:reception_date_begin].blank? && params[:reception_date_end].blank?)

    @uploads = Image.search with: with, order: sort, per_page: per_page, page: page
    @nb_up = {}
    facets = Image.facets("", with)
    @nb_up = facets[:provider_id]

    respond_to do|format|
      #format.html { render stream: true, layout: "statistics" }
      #format.js { render stream: true }
      format.html { render layout: "statistics" }
      format.csv {send_data Image.uploads_to_csv(@uploads), filename: "envois_" + Time.now.strftime("%Y-%m-%d_%H-%M") + ".csv", type: 'text/csv; charset=utf-8; header=present'}
    end

  end

  def create
    phtab = []
    params[:photo][:photo].each do |p|
      photo = Photo.new(photo: p, user_id: params[:photo][:user_id], city: params[:photo][:city],
                        description: params[:photo][:description], reportage: params[:photo][:reportage],
                        credit: params[:photo][:credit], up_country: params[:photo][:up_country], source: params[:photo][:source])
      if photo.photo_integrity_error
        redirect_to action: :new, notice: I18n.t('uploads.error_jpg')
        return
      else
        photo.save
        phtab << photo.id
      end
    end
    if phtab.empty?
      redirect_to action: :new
    else
      redirect_to action: 'edit', id: phtab.first, phtab: phtab
    end
  end

  def update
    @photo = Photo.find(params[:id])
    if @photo.update_attributes(permitted_params)
      photo = Photo.find(@photo.id)
      photo_name = photo.photo_identifier
      name_txt = photo_name.gsub(".jpg", "")
      name_txt.gsub!(".JPG", "")
      name_txt = "#{name_txt}.csv"
      import_dir = "1"
      target  = "/tmp/#{name_txt}"
      credit = photo.credit.nil? ? "" : photo.credit
      content_label = "2:55,2:105,2:120,2:121,2:101,2:90,2:80,2:110,2:115,2:116,2:25,2:40,3:213,3:220,3:230,3:255\n"
      content_data = photo.date_photo.nil? ? "\"\" ," : "\"" + photo.date_photo.to_s + "\","
      content_data += photo.reportage.nil? ? "\"\" ," : "\"" + photo.reportage.to_s + "\","
      content_data += photo.description.nil? ? "\"\" ," : "\"" + photo.description.to_s + "\","
      content_data += photo.reportage.nil? ? "\"\" ," : "\"" + photo.reportage.to_s + "\","
      content_data += photo.up_country.nil? ? "\"\" ," : "\"" + photo.up_country.to_s + "\","
      content_data += photo.city.nil? ? "\"\" ," : "\"" + photo.city.to_s + "\","
      content_data += "\"\","
      content_data += "\"\","
      content_data += photo.source.nil? ? "\"\" ," : "\"" + photo.source.to_s + "\","
      content_data += "\"" + credit + "\","
      content_data += photo.keywords.nil? ? "\"\" ," : "\"" + photo.keywords.to_s + "\","
      content_data += "\"\","
      content_data += "\"\","
      content_data += "\"\","
      content_data += "\"\","
      content_data = content_data.squish
      content_data += "\"" + import_dir + "\"\n"
      content = content_label + content_data

      File.open(target, "w+:UTF-8") do |f|
        f.write(content)
      end
      flash[:notice] = "Photo envoyée pour traitement"

      if Server.itself?(VINGTMINUTES_SERVER_NAME)
        if current_user.city.blank?
          vers = "/mnt/pixpush/Paris/JPEG_CSV/"
        else
          vers = "/mnt/pixpush/#{current_user.city.capitalize}/JPEG_CSV/"
        end
        begin
          FileUtils::cp target, "#{vers}#{name_txt}"
          FileUtils::cp "public#{@photo.photo_url}", "#{vers}#{photo_name}"
        rescue => e
          logger.info "e = #{e.inspect}"
          flash[:notice] = "Erreur envoi photo : #{e}"
        end
      end

      phtab = []
      phtab = params[:tabph].split('#')
      if phtab.count > 1
        p_id = params[:id]
        phtab.delete(p_id)
        credit = @photo.credit.nil? ? "" : @photo.credit
        source = @photo.source
        city = @photo.city
        reportage = @photo.reportage
        pays = @photo.up_country
        description = @photo.description
        date_photo = @photo.date_photo
        keywords = @photo.keywords
        phtab.each do |p|
          Photo.update(p, credit: credit, city: city, reportage: reportage, description: description, date_photo: date_photo, keywords: keywords, up_country: pays, source: source)
          photo = Photo.find(p)
          photo_name = photo.photo_identifier
          credit = photo.credit
          name_txt = photo_name.gsub(".jpg", "")
          name_txt.gsub!(".JPG", "")
          name_txt = "#{name_txt}.csv"
          target  = "/tmp/#{name_txt}"
          content_label = "2:55,2:105,2:120,2:121,2:101,2:90,2:80,2:110,2:115,2:116,2:25,2:40,3:213,3:220,3:230,3:255\n"
          content_data = photo.date_photo.nil? ? "\"\" ," : "\"" + photo.date_photo.to_s + "\","
          content_data += photo.reportage.nil? ? "\"\" ," : "\"" + photo.reportage.to_s + "\","
          content_data += photo.description.nil? ? "\"\" ," : "\"" + photo.description.to_s + "\","
          content_data += photo.reportage.nil? ? "\"\" ," : "\"" + photo.reportage.to_s + "\","
          content_data += photo.up_country.nil? ? "\"\" ," : "\"" + photo.up_country.to_s + "\","
          content_data += photo.city.nil? ? "\"\" ," : "\"" + photo.city.to_s + "\","
          content_data += "\"\","
          content_data += "\"\","
          content_data += photo.source.nil? ? "\"\" ," : "\"" + photo.source.to_s + "\","
          content_data += "\"" + credit + "\","
          content_data += photo.keywords.nil? ? "\"\" ," : "\"" + photo.keywords.to_s + "\","
          content_data += "\"\","
          content_data += "\"\","
          content_data += "\"\","
          content_data += "\"\","
          content_data = content_data.squish
          content_data += "\"" + import_dir + "\"\n"
          content = content_label + content_data

          File.open(target, "w+:UTF-8") do |f|
            f.write(content)
          end
          flash[:notice] = "Photos envoyées pour traitement"
          if Server.itself?(VINGTMINUTES_SERVER_NAME)
            begin
              FileUtils::cp target, "#{vers}#{name_txt}"
              FileUtils::cp "public#{photo.photo_url}", "#{vers}#{photo_name}"
            rescue => e
              logger.info "e = #{e.inspect}"
              flash[:notice] = "Erreur envoi photo : #{e}"
            end
            @photo.date_photo = EXIFR::JPEG.new("public#{@photo.photo.url}").date_time
            @photo.description = EXIFR::JPEG.new("public#{@photo.photo.url}").image_description
            @photo.reportage = ""
          end
        end
      end
      redirect_to action: :new
    else
      phtab = []
      phtab = params[:tabph].split('#')
      @photos = Photo.where(id: phtab)
      @phtab = params[:tabph]
      render :edit
    end
  end

  def destroy
  end

  def edit
    @photo = Photo.find(params[:id])
    phtab = params[:phtab]
    if Server.itself?(VINGTMINUTES_SERVER_NAME)
      @photo.date_photo = EXIFR::JPEG.new("public#{@photo.photo.url}").date_time
      @photo.description = EXIFR::JPEG.new("public#{@photo.photo.url}").image_description.force_encoding("UTF-8")
      @photo.reportage = ""
    end
    @photos = Photo.where(id: phtab)
    @phtab = phtab.map{|i| i.to_s}.join('#')
    @countries = []
    IptcCountry.order(:fr).all.collect{ |p| @countries << p.fr.upcase }
    render layout: false
  end

  def new
    @photo = Photo.new
    @user = current_user
    @title = "PixTech"
    @title += " - 20Minutes" if Server.itself?(VINGTMINUTES_SERVER_NAME)
    @title = "Pixtrakk" if Server.itself?(PTREF_SERVER_NAME)
    flash[:notice] = params[:notice] if params[:notice]
    render layout: false
  end

  def show
  end

  private

  def permitted_params
    params.require(:photo).permit!
  end

end

