# encoding: ASCII-8BIT
#
# CopyProfileImage. class which defines various attributes and behaviours
# which are used to copy profile images from legacy to MPTest02 sever
#
# Author::    Hanumantharaju  (mailto:hanumantharaju.tswamy@costrategix.com)
# Copyright:: Copyright (c) 2015 Crossroads
# License::   MIT
#
# Initiating this class leads to copying profile image
#
class CopyProfileImage

  #
  # Initialize the copying profile image
  #
  def initialize
    self.copy_image
  end

  #
  # Function used to copy profile image
  #
  def copy_image

    begin
      optimized_image_log_file = 'optimized_profile_image.txt'
      image_migration_log_file = 'profile_image_migration.log'
      File.delete(image_migration_log_file) if File.exist?(image_migration_log_file)
      person_list = Mediahelper.get_person_list
      puts String::colorize("\nCopying profile image...!\n", 'green')
      image_source_path = "#{Immutable.config.profile_image_source_path}"
      destination_image_path = "#{Immutable.config.profile_image_destination_path}"
      if (Dir.entries(destination_image_path) - %w{ . .. }).empty?
        File.delete(optimized_image_log_file) if File.exist?(optimized_image_log_file)
      end
      person_list.each do |person_data|
        source_image = "#{image_source_path}#{person_data[:profile_image]}"
        file_name = File.basename(source_image)

        if File.exists?(source_image.to_s)
          file_extension = File.extname(file_name).downcase
          if file_extension.empty? || file_extension.nil?
            file_extension = '.jpg'
          end
          new_file_name = "#{person_data[:person_id]}#{file_extension}"
          file_to_resize = "#{destination_image_path}/#{new_file_name}"
          unless File.exists?(file_to_resize)
            begin
              puts 'Person id: '+ String::colorize(person_data[:person_id], 'green')
              puts 'Image name: '+ String::colorize(file_name, 'green')
              #self.resize_image(source_image, destination_image_path, new_file_name, 800)
              command = "convert '#{source_image}'  -strip -resize 800x800\\> -quality 80 #{destination_image_path}/#{new_file_name}"
              system(command)
            rescue StandardError => e
              puts "\t\tError in resizing image #{person_data[:profile_image]}\n"
              puts "\tError: #{e}\n"
              log_message = "\n"
              log_message += "person id: #{person_data[:person_id]}\n \t\tError in resizing image: #{person_data[:profile_image]}"
              File.open(image_migration_log_file, 'a+') { |f| f.write(log_message + "\n") }
            ensure
              puts 'Status: '+ String::colorize('Done', 'green')
              puts "\n"
            end
          end
        else
          puts 'Person id: '+ String::colorize(person_data[:person_id])
          puts 'Image not found: '+ String::colorize(file_name)
          puts "\n"
          log_message = "================================================================================\n"
          log_message += " person id: #{person_data[:person_id]}\n #{person_data[:profile_image]} image not found"
          File.open(image_migration_log_file, 'a+') { |f| f.write(log_message + "\n") }
        end
        puts "\n"
      end
      #puts String::colorize('Optimize images', 'green')
      #self.optimize_images(destination_image_path, optimized_image_log_file)
      puts 'Status: '+String::colorize('Done', 'green')
    rescue Exception => e
      puts "Error:\n #{e}"
      return
    end
  end

  def resize_image(source, destination, file_name, size)
    img = Magick::Image.read(source).first
    width = img.columns
    height = img.rows
    destination = "#{destination}/#{file_name}"
    if width > 800
      resized = img.resize_to_fit(size)
      resized.write(destination) do
        self.quality = 100
      end
      # free up RAM
      resized.destroy!
    else
      FileUtils.cp(source, destination)
    end
    img.destroy!
  end

  # Used to optimize images
  def optimize_images(dest_image_path,log_file)
    Dir.foreach(dest_image_path) do |image_file|
      begin
        file_exist = `grep "#{image_file}" optimized_profile_image.txt`
        next if image_file['.svn'] or image_file == '.' or image_file == '..' or !file_exist.empty?
        puts 'Optimizing image: '+ String::colorize(image_file, 'green')
        image_optimize = ImageOptim.new({:nice => 20, :svgo => false, :pngout => false, :pngquant => false})
        image_to_optimize = "#{dest_image_path}/#{image_file}"
        image_optimize.optimize_image!(image_to_optimize)
        File.open(log_file, 'a+') { |f| f.write("[#{DateTime.now}] "+image_file + "\n") }
        puts "\tStatus: "+ String::colorize('Done', 'green')
      rescue StandardError => e
        puts "\t\tError in optimizing image #{image_file}\n"
        puts "\tError: #{e}"
      ensure
      end
    end
  end

  def create_directory(director_name)
    unless File.directory?(director_name)
      FileUtils.mkdir_p(director_name)
    end
  end

    #
    # Function to check if download is needed
    #
    # * gets the file URL
    # * destination path of local
    #
    def check_file_to_download(filename, file, destination_path)
      begin
        uri = Mediahelper.get_url_encoded_file(file)
        full_destination_path = "#{destination_path}#{filename}"
        unless File.exists?(full_destination_path.to_s)
          Mediahelper.http_download_uri(uri, full_destination_path)
        else
          puts "Skipping download for '#{filename}' It already exists."
        end
        full_destination_path
      rescue Errno::EPIPE
        puts 'Pipe error. Retrying...........'
      end
    end

end