include ActionView::Helpers::NumberHelper

class ImagesController < ApplicationController

  def show
    @image = Image.find(params[:id])

    respond_to do |format|
      format.xml { render :xml => @image }
    end
  end

  def authors_list
    @authors = {}
    session_pixtech = session[:pixtech].partition('_vitrine')[0]

    if Server.itself?(PIXADMIN_SERVER_NAME)
      stocks = Provider.joins(:pixtech).where(pixteches: {name: session_pixtech}, providers: {provider_type_id: 1}).pluck('providers.id, providers.string_key, providers.name')
    else
      stocks = Provider.joins(:pixtech).where(pixteches: {name: session_pixtech}, providers: {id: session[:provs]}).pluck('providers.id, providers.string_key, providers.name')
    end

    # Authors list on PixAdmin
    if Server.itself?(PIXADMIN_SERVER_NAME) && Pixways.get_pixtech_param_value(session_pixtech,'authors_list_using_creator') != 'true' # Authors list for admin using authors provider name
      authors = Provider.joins(:pixtech).where(pixteches: {name: session_pixtech}, providers: {provider_type_id: 2}).select('providers.id, providers.name, providers.pp_string_key, providers.description').order('providers.name')
      authors.each do |auth|
        stock = stocks.detect{|s| s[1]==auth.pp_string_key}
        stock = ['',auth.pp_string_key,auth.pp_string_key] if stock.blank?
        nb_images_intern = Image.search_count with: {provider_id: auth.id, content_error: false}
        if Pixways.get_pixtech_param_value(session[:pixtech],'automatic_images_flow')!='true'
          nb_images_pp1 = Image.search_count with: {provider_id: auth.id, flow: 1, content_error: false}
          nb_images_pp2 = Image.search_count with: {provider_id: auth.id, flow: 2, content_error: false}
        else
          nb_images_pp1 = ''
          nb_images_pp2 = ''
        end
        hr_access = session[:provhd][auth.id]==1 ? 1 : 0
        email = auth.provider_contacts.find_by(main:true).email rescue '' # For export list
        @authors[auth.id]=[auth.name,stock[2],auth.description,nb_images_intern,nb_images_pp1,nb_images_pp2,hr_access,email]
      end
    elsif Server.itself?(PIXADMIN_SERVER_NAME) && Pixways.get_pixtech_param_value(session_pixtech,'authors_list_using_creator') == 'true' # Authors list for admin using images creator
      authors = Provider.joins(:images,:pixtech).where(pixteches: {name: session_pixtech}, providers: {provider_type_id: 2}, images: {content_error: false}).select('providers.id, images.creator, providers.name, providers.pp_string_key, providers.string_key, providers.description').group(:provider_id, :creator).order('providers.id, images.creator')
      authors.each do |auth|
        unless auth.creator.blank?
          nb_images_intern = Image.search_count conditions: {creator: '"'+auth.creator+'"'}, with: {provider_id: auth.id, content_error: false}
          if Pixways.get_pixtech_param_value(session[:pixtech],'automatic_images_flow')!='true'
            nb_images_pp1 = Image.search_count conditions: {creator: '"'+auth.creator+'"'}, with: {provider_id: auth.id, flow: 1, content_error: false}
            nb_images_pp2 = Image.search_count conditions: {creator: '"'+auth.creator+'"'}, with: {provider_id: auth.id, flow: 2, content_error: false}
          else
            nb_images_pp1 = ''
            nb_images_pp2 = ''
          end
          hr_access = session[:provhd][auth.id]==1 ? 1 : 0
          email = auth.provider_contacts.find_by(main:true).email rescue '' # For export list
          @authors[[auth.creator,auth.name]]=[auth.creator,auth.name,auth.description,nb_images_intern,nb_images_pp1,nb_images_pp2,hr_access,email,auth.id]
        end
      end
    else #Authors list for clients using images creator
      if Pixways.get_pixtech_param_value(session[:pixtech],'show_providers_panel','true') == 'true'
        @authors = Provider.joins(:images).where("providers.id in (?) and images.content_error=? and images.creator !=?",stocks.transpose[0], 0, "NULL").group(:provider_id,'providers.name',:creator).order('images.creator').count
      else
        @authors = Provider.joins(:images).where("providers.id in (?) and images.content_error=? and images.creator !=?",stocks.transpose[0], 0, "NULL").group(:creator).order('images.creator').count
      end
    end

    respond_to do|format|
      format.html {
        render layout: 'simple'
      }
      format.csv {
        send_data Image.export_authors_list(@authors,session[:creator_word],session[:provider_word],session[:pixtech],Pixways.get_pixtech_param_value(session[:pixtech],'show_providers_panel') == 'true'), filename: I18n.t(:creator_list_csv,creator_word: I18n.t(session[:creator_word])) + '_' + Time.now.strftime('%Y-%m-%d_%H-%M') + '.csv', type: 'text/csv; header=present'
      }
    end
  end

  def tst_jcrop
    if params[:id]
      idi = params[:id].to_i
    else
      idi = 36070272
    end
    @image = Image.find(idi)
    siz = []
    s = ImageSize.path("public#{@image.medium_location}").size
    siz = s.to_s.split('x')
    wm = siz[0].to_f
    hm = siz[1].to_f
    @xratio = ratio_x(@image.max_avail_width, wm)
    @yratio = ratio_y(@image.max_avail_height, hm)
    render layout: 'simple'
  end

  def valid_crop
    im = Image.find(params[:img].to_i)
    if params[:button]
      redirect_to home_path
    else
      @image = im.medium_location
      @image_id = im.id
      unless params[:x1].blank?
        @x = params[:x1].to_i
        @y = params[:y1].to_i
        @w = params[:w].to_i
        @h = params[:h].to_i
        img_ori = Magick::Image.read("public#{@image}").first
        img_ori.crop!(@x,@y,@w,@h)
        img_ori.write("#{Rails.root}/public/c_#{im.original_filename}")
        img_ori.destroy!
        @image = "/c_#{im.original_filename}"
      end
      render layout: 'simple'
    end
  end

  def definitive_crop
    im = Image.find(params[:img].to_i)
    if params[:button]
      redirect_to action: 'tst_jcrop', id: im
    else
      hr_location = "public/#{im.original_filename}"
      get_ms_file(hr_location, im.ms_picture_id, MS[im.ms_id])
      unless params[:x1].blank?
        x = params[:x1].to_i
        y = params[:y1].to_i
        w = params[:w].to_i
        h = params[:h].to_i
        siz = []
        s = ImageSize.path("public#{im.medium_location}").size
        siz = s.to_s.split('x')
        wm = siz[0].to_f
        hm = siz[1].to_f
        xratio = im.max_avail_width/wm
        yratio = im.max_avail_height/hm
        x = x*xratio
        y = y*yratio
        w = w*xratio
        h = h*yratio
        img_ori = Magick::Image.read(hr_location).first
        img_ori.crop!(x.to_i,y.to_i,w.to_i,h.to_i)
        img_ori.write("#{Rails.root}/public/c_#{im.original_filename}")
        img_ori.destroy!
        hr_location = im.original_filename
      end
      @id = im.id
      @img = "c_#{im.original_filename}"
      @s = ImageSize.path("public/#{@img}").size
      conv = []
      conv = @s.to_s.split('x')
      w = ratio_x(conv[0].to_i,1)
      h = ratio_y(conv[1].to_i,1)
      @cm = "#{w.to_i}x#{h.to_i}"
      @p = number_to_human_size(File.size("public/#{@img}"))
      render layout: 'simple'
    end
  end

  def etna_leg
    @id = params[:id].to_i
    @img = ''
    @img = params[:img] if params[:img]
    @leg = Image.find(@id).description
    render layout: nil
  end

  def horby_send
    if params[:button]
      flash[:alert] = 'Téléchargement annulé'
    else
      img_id = []
      leg = ''
      st_alert = 'Image(s) envoyée(s) dans Etna : '
      if params[:id]
        img_id << params[:id].to_i
        leg = params[:leg]
        hr_location = params[:img]
      end
      if params[:ids]
        params[:ids].each{ |i| img_id << i }
      end
      img_id.each do |i|
        im = Image.find(i)
        if hr_location.blank?
          hr_location = "public/#{im.original_filename}"
          get_ms_file(hr_location, im.ms_picture_id, MS[im.ms_id])
        end
        id20m = envoi_horby(hr_location, leg)
        if id20m == 'Erreur'
          st_alert = "#{im.original_filename} : erreur envoi vers Etna"
        else
          Statistic.create(image_id: i, user_id: current_user.id, operation_label_id: 2, id20min: id20m)
          Image.update(i, id20min: id20m)
          FileUtils.rm hr_location
          st_alert += " #{im.original_filename}"
        end
      end
      flash[:alert] = st_alert
    end
    render layout: nil
    #redirect_to home_path
  end

  def print_send
    dossier = []
    dossier = params[:dos].split('@')
    img_id = dossier[1].to_i
    dos = dossier[0]
    im = Image.find(img_id)
    nom = params[:nom_print].blank? ? im.original_filename : "#{params[:nom_print]}.jpg"
    if dossier[2]
      hr_location = "public/#{dossier[2]}"
    else
      hr_location = "public/#{im.original_filename}"
      get_ms_file(hr_location, im.ms_picture_id, MS[im.ms_id])
    end
    begin
      FileUtils.mv( hr_location, "#{dos}/#{nom}" )
      Statistic.create_stat(current_user.id, img_id, 2)
      flash[:alert] = "#{nom} envoyée dans le dossier Print"
    rescue => e
      logger.info "e = #{e.inspect}"
      flash[:alert] = "Erreur envoi #{nom}"
    end
    redirect_to home_path
  end

  def edit
    @image = Image.find(params[:id])
    @record_id = params[:record_id]
    @tri = params[:tri]
    @errtyp = params[:errtyp]
    render layout: 'simple'
  end


  def update
    unless params[:button]
      @image = Image.find(params[:id])
      if @image.update_attributes(permitted_params)
        Image.envoi_MS(params[:id].to_i)
        if params[:record_id].empty?
          redirect_to home_path
        else
          config_db_ms = Rails.configuration.database_configuration['ms_db']
          client = Mysql2::Client.new(host: config_db_ms['host'], database: config_db_ms['database'], username: config_db_ms['username'], password: config_db_ms['password'])
          client.query("update MessageToPA set mtpa_done=1 where mtpa_id = #{params[:record_id]}")
          client.close
          redirect_to controller: 'pictures_control', action: 'index', tri: params[:tri], errtyp: params[:errtyp]
        end
      else
        render action: :edit
      end
    else
      if params[:record_id].empty?
        redirect_to home_path
      else
        redirect_to controller: 'pictures_control', action: 'index', tri: params[:tri], errtyp: params[:errtyp]
      end
    end
  end

  private

  def get_ms_file(orig_file, ms_img_id, url)
    requ = marek_request_build(ms_img_id)
    uri = URI("#{url}/cgi-bin/download_pixpalace.zip")
    res = Net::HTTP.post_form(uri, 'from' => requ)
    tempfile = Tempfile.new('wb')
    tempfile.binmode
    tempfile.write(res.body)
    tempfile.rewind
    File.open(orig_file, 'wb'){ |f| f.write(tempfile.read) }
    tempfile.close
    tempfile.unlink
  end

  def envoi_horby(img, leg)
    url_key = 'media?upload_to_krakatoa=1&crop_white_borders=1'
    url_key += "&caption=#{leg}" unless leg.blank?
    #secret_key = 'secret'
    endpoint_url = 'http://dam.20minutes.fr/'
    safeurl = URI.encode("#{endpoint_url}#{url_key}".strip)

    begin
      res = RestClient.post(safeurl,
                            {
                              file: File.new(img, 'rb')
                            }, 'source' => 'Pixpalace')
    rescue => e
      logger.info"**** rescue #{e.inspect}"
      return 'Erreur'
    end
    retour = JSON.parse(res.body)
    retour['_id']
  end

  def ratio_x(whr, wlr)
    x_ratio = ((whr/wlr)/300)*2.54
    x_ratio
  end

  def ratio_y(hhr, hlr)
    y_ratio = ((hhr/hlr)/300)*2.54
    y_ratio
  end

  def marek_request_build(ms_pic_id)
    params = []
    params << '9Pu0NkL41'
#    if ms_pic_id.to_s.length > 20
#      params << marek_decrypt(ms_pic_id)
#    else
    params << ms_pic_id
#    end
    params << current_user.title.server.name
    params << request.remote_ip
    params << current_user.title.name
    params << current_user.login
    marek_crypt(params.join('@@@'))
  end

  def permitted_params
    params.require(:image).permit(:date_created, :headline, :description, :country, :city,
                                  :source, :creator, :rights, :credit, :subject, :instructions)
  end

end
