# encoding: utf-8
#require 'capistrano'
require 'fileutils'
require 'net/ftp'
require 'mysql2'

class LightBoxesController < ApplicationController

  skip_before_action :login_required, only: [:lb_share]
  before_action :current_user_light_boxes, except: :lb_share
  after_action :store_current_light_box, except: [:update, :lb_share, :pixtech_envoi_pp]

  def show
    @light_box = @light_boxes.find(params[:id])
    redirect_to action: 'index' if @light_box.nil?
    init_html
  end

  def index
    @light_box = @light_boxes.find_by_id(session[:active_light_box]) || @light_boxes.last
    init_html
    render action: 'show'
  end

  def edit
    @light_box = @light_boxes.find_by_id(params[:id])
  end

  def destroy
    @light_boxes.find(params[:id]).destroy
    @light_box = @light_boxes.last
    init_html
    render action: 'show'
  end

  def create
    @light_box = @light_boxes.create(permitted_params.merge(title: current_user.title))
    init_html
    render action: 'show'
  end

  def update
    @light_box = @light_boxes.find(params[:id])
    @light_box.update_attributes(permitted_params)
    init_html
    render action: 'show'
  end

  def lb_share
    light_box = LightBox.find_by_hash_code(params[:id])
    if light_box.nil?
      redirect_to root_path
    else
      @medias = LightBoxImage.where(light_box_id: light_box.id).order('position DESC').collect{ |i| Image.find(i.image_id.to_i) if i.image_id.to_i > 0 }
      @share = @medias.first.id
      @display_thumb = true
      render layout: 'medias'
    end
  end

  def reception_date_update
    @light_box = @light_boxes.find(params[:id])
    lb = @light_box.name
    imgs = []
    params[:ids].each do |i|
      im = Image.where(id: i).select(:id, :ms_image_id, :original_filename, :file_name, :provider_id, :creator, :content_error).first
      imgs << im if (im.has_right(current_user,'HD') && (im.content_error === false))
    end
    imgs.compact!
    imgs.sort
    if imgs.count < 1
      msg = I18n.t('no_admin_rights')
    else
      updat = {}
      im_name = {}
      imgs.each do |i|
        p = i.provider_id
        updat[p]= [] unless updat.key? p
        updat[p] << i.ms_image_id
        im_name[p]= [] unless im_name.key? p
        im_name[p] << i
      end
      util = current_user
      msg = ''
      updat.keys.each do |p|
        prov = Provider.find(p)
        rp = RefreshProvider.find_by(provider_id: p)
        rp_nb_updated = UpdatedListProvider.joins(:refresh_provider).where(refresh_providers:{provider_id: p},created_at: Time.now().beginning_of_month..Time.now().end_of_month).sum(:nb_photos)
        nb = updat[p].count
        if (rp_nb_updated + nb) <= rp.total_update
          updating_images(im_name[p], prov.string_key)
          UserMailer.warn_update_user(im_name[p], util, lb, prov.name, session[:pixtech]).deliver_now
          UpdatedListProvider.create(refresh_provider_id: rp.id, nb_photos: nb, action_date: Time.now, visionneuse: lb)
          tot = rp_nb_updated + nb
          mois = I18n.l Date.today, format: '%B'
          msg += "\n" + prov.name + " : " + I18n.t('valid_top', tot: nb, mm: mois, rest: rp.total_update-tot)
        else
          msg += "\n" + prov.name + " : " + I18n.t('error_top', tot: nb, total_dispo: rp.total_update)
        end
      end
    end
    @notice_adm = msg
    init_html
    render action: 'show'
  end

  def send_and_delete
    @light_box = @light_boxes.find(params[:id])
    lb = @light_box.name
    msg = ''
    ims = []
    images_list = []
    server_dest = params[:serv_dest] ? params[:serv_dest] : ''
    server_src = Server.find_by_is_self(true).name
    params[:ids].each do |i|
      im = Image.where(id: i).select(:id, :original_filename, :file_name, :medium_location, :provider_id, :content_error, :creator, :flow).first
      unless im.nil? #ToDo : there should not have pictures in lght_box not existing in images table => check image destroy with associations
        if (im.has_right(current_user,'HD') && (im.content_error === false))
          unless (Server.itself?(VINGTMINUTES_SERVER_NAME) && !(im.provider.local) && current_user.is_provider_admin?)
            ims << im
            images_list << im.file_name unless (server_dest == 'pp1' || server_dest == 'pp2')
            if im.provider.is_pixtech_author?
              # Problem with pictures on PP2, so that can't be found on PixAdmin
              # image_pp = Image.joins(:provider).where(original_filename: im.original_filename, providers: {string_key: im.provider.pp_string_key}).first
              # images_list << image_pp.file_name unless image_pp.nil?
              images_list << im.provider.pp_string_key+"."+im.provider.string_key.downcase.partition("#{im.provider.pp_string_key.downcase}_")[2]+"_"+im.file_name.sub("#{im.provider.string_key}.",'') #file_name with author prefix included in the name, after agency prefix (new process)
              images_list << im.provider.pp_string_key+"."+im.provider.string_key+"_"+im.file_name.sub("#{im.provider.string_key}.",'') #Christophel PixTech
              images_list << "#{im.provider.pp_string_key}#{im.file_name.sub(im.provider.string_key,'')}" #file_name with only agency prefix (like old Saif authors or PixTech without author buttons like MYOP)
            end
            im.update(flow: 0) if ((im.flow == 1 && server_dest == 'pp1') || (im.flow == 2 && server_dest == 'pp2'))
          end
        end
      end
    end
    ims.compact!
    ims.sort
    if ims.count < 1
      msg = I18n.t('no_admin_rights')
    else
      util = current_user
      if params[:pp2]
        send_to_pp2 = true
        msg = I18n.t 'lb_transfert'
        UserMailer.warn_pp2_user(ims, util, lb, session[:pixtech]).deliver_now
      else
        send_to_pp2 = false
        msg = I18n.t('send_and_delete_inprocess')
        UserMailer.warn_user(ims, util, lb, server_src, session[:pixtech], server_dest).deliver_now
      end
      image_deletion(images_list, util.title.name.gsub(/[^a-zA-Z0_9]/, ''), server_dest, send_to_pp2)
    end
    @notice_adm = msg
    init_html
    render action: :show
  end

  def send_and_demand
    @light_box = @light_boxes.find(params[:id])
    lb = @light_box.name
    prov = []
    imgs = {}
    im_prov = {}
    im_creator = {}
    params[:ids].each do |i|
      Statistic.create_stat(current_user.id, i, 3)
      img = Image.where(id: i).select(:original_filename, :provider_id, :thumb_location, :creator).first
      im = img.original_filename
      p = img.provider_id
      prov << p
      imgs[im] = img.thumb_location
      im_creator[im] = img.creator if img.provider.is_pixtech_stock?
      im_prov[p] = [] unless im_prov.key? p
      im_prov[p] << im
    end
    prov.compact!
    prov.uniq!
    prov.each do |p|
      prov_img = Provider.find(p)
      prov_contact = []
      ProviderContact.where(provider_id: p, receive_demand: true).collect{ |pc| prov_contact << pc.email }
      unless prov_contact.blank?
        UserMailer.pp2_dw_provider(im_prov[p], imgs, prov_img.name, prov_contact, current_user, params[:definition],im_creator).deliver_now
      end
      UserMailer.pp2_dw_user(im_prov[p], imgs, prov_img.name, prov_contact, current_user, lb, params[:definition]).deliver_now
    end
    @notice_adm = I18n.t('demand_sent')
    init_html
    render action: :show
  end

  def pixtech_envoi_pp
    if params[:pictures_list]
      Image.delay.send_to_MS(params,current_user,session[:pixtech])
      redirect_to :back
    else
      @light_box = @light_boxes.find(params[:id])
      msg = I18n.t('lb_transfert')
      if params[:pp2]
        dest = 'PP2'
        server = 'PixPalace 2'
        img_flow_to_check = 1
        server_checked = 'PixPalace'
      else
        dest = 'PP'
        server = 'PixPalace'
        img_flow_to_check = 2
        server_checked = 'PixPalace 2'
      end
      lb = @light_box.name
      imgs = []
      imgs_rejected = []
      params[:ids].each do |i|
        im = Image.where(id: i).select(:id,:ms_image_id,:original_filename,:file_name,:creator,:provider_id,:content_error,:flow,:hires_location).first
        if im.provider.is_pixtech_author? && im.content_error === false
          if  img_flow_to_check == im.flow
            imgs_rejected << im
          else
            imgs << im
          end
        end
      end
      imgs.compact!
      imgs.sort
      if imgs.count < 1
        if imgs_rejected.count  < 1
          msg = I18n.t('pixtech_no_internal_images')
        else
          msg = I18n.t('pixtech_duplicate', dup_nb: imgs_rejected.count, serv_dup: server_checked)
        end
      else
        util = current_user
        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'])
        imgs.each do |i|
          csv = "3:238\r\n\"#{dest}\""
          case dest
          when 'PP'
            i.update(flow: 1)
          when 'PP2'
            i.update(flow: 2)
          end
          client.query("insert into MetadataFromPA set mdfpa_pic_id=#{i.ms_image_id}, mdfpa_csv='#{Mysql2::Client.escape(csv)}', mdfpa_created_at=now()")
        end
        client.close
        msg = I18n.t('lb_transfert_dup', dup_nb: imgs_rejected.count, serv_dup: server_checked) if imgs_rejected.count > 0
        UserMailer.warn_pixtech(imgs, imgs_rejected, util, lb, server, server_checked,session[:pixtech]).deliver_now
      end
      @notice_adm = msg
      init_html
      render action: :show
    end
  end

  private

  def current_user_light_boxes
    @light_boxes ||= current_user.light_boxes
  end

  def store_current_light_box
    session[:active_light_box] = @light_box.id
  end

  def init_html
    @lb_images = @light_box.images.where(content_error: 0).order('position')
    @panier_size = @lb_images.sum(:hr_size) rescue 0 unless Server.itself?(PP2_SERVER_NAME)
    @nopicto = no_picto
  end

  def updating_images(imgs, stringkey)
    local_tmp_path = '/home/pix/support/tmp/'
    capistrano_path = '/home/pix/capistrano/pixways/'
    logs_path = "/var/log/pixways/update_images/#{Time.now.strftime('%Y%m%d')}/"

    file_name = Time.now.strftime('%Y-%m-%d-%Hh%Mm%S')+"_#{stringkey}"
    main_log_file_name="#{logs_path}#{file_name}_main.log"
    main_error_log_file_name="#{logs_path}#{file_name}_main.error-log"
    pictures_list = "#{local_tmp_path}#{file_name}.txt"
    ini_file = "#{local_tmp_path}#{file_name}.ini"

    File.open(pictures_list,'wb') do |f|
      imgs.each do |i|
        f.write("#{i.ms_image_id}\n")
      end
    end

    #create logs folder if doesn't exist and call ultra_cap_delete
    update_command = "mkdir -p #{logs_path};#{capistrano_path}ultra_cap_update.sh 'pixpalace:pictures_update -s pictures_list=#{pictures_list}' 1>>#{main_log_file_name} 2>>#{main_error_log_file_name}"
    File.open(ini_file,'wb') do |f|
      f.write(update_command)
    end

    #execute the command as a background task
    pid = Process.spawn("at -f #{ini_file} now")
    Process.detach(pid)
  end

  def permitted_params
    params.require(:light_box).permit(:name)
  end

end