# encoding: utf-8 
require 'mongo'

namespace :gallery_album do
  task :gallery_album_to_new => :environment do

    @db = Mongoid.database

    category_name = "gallery_category"
    model_name = "album"
    fs_files = @db['fs.files']
    fs_chunks = @db['fs.chunks']
    collection_category = @db[category_name.pluralize]
    old_collection_db = @db['gallery_albums']
    old_image_collection_db = @db['gallery_images']
    categories = collection_category.find.entries if collection_category
    collection_model = @db[model_name.pluralize]
    collection_buffer_category = @db['buffer_categories']
    collection_prototype_auth = @db['prototype_auths']

    if categories.present?
      module_app = ModuleApp.where(key: 'gallery').first
      if module_app.try(:has_category)
        categories.each do |category|
          new_category = module_app.categories.build
          new_category.title_translations = category['name']
          new_category.disable = false
          new_category.save

          old_module_db = old_collection_db.find(gallery_category_id: category['_id']).entries
          if old_module_db.present?
            old_module_db.each do |old_module|

              new_main_db = Album.new
              new_main_db.name_translations = old_module['name']
              new_main_db.description_translations = old_module['description']
              new_main_db.category_id = new_category.id
              new_main_db.updated_at = old_module['updated_at']
              new_main_db.created_at = old_module['created_at']
              new_main_db.save

              old_module_db_images = old_image_collection_db.find(gallery_album_id: old_module['_id']).entries
              if old_module_db_images.present?
                old_module_db_images.each do |old_module_db_image|

                  new_image = new_main_db.album_images.build

                  tmp_file = File.new(old_module_db_image['file'], 'w+')

                  file_url = "gallery/gallery_image/file/#{old_module_db_image['_id']}/#{old_module_db_image['file']}"

                  tmp_file.write(Mongo::GridFileSystem.new(Mongoid.database).open(file_url, 'r').read.force_encoding("UTF-8"))

                  new_image.file = tmp_file

                  new_image.save

                  # # delete copy file
                  FileUtils.rm_f(tmp_file)

                  #del old file
                  ffs = fs_files.find(filename: "#{file_url}").first  

                  fs_chunks.remove(files_id: ffs["_id"])

                  fs_files.remove(filename: "#{file_url}")

                end
              end

            end
          end

          collection_model.find("#{category_name}_id" => category['_id']).each do |object|
            object['category_id'] = new_category.id
            object.delete("#{category_name}_id")
            collection_model.save object
            collection_buffer_category.save ({ '_type' => 'BufferCategory', 'category_id' => new_category.id, 'categorizable_type' => model_name.camelize, 'categorizable_id' => object['_id'] })
          end
          object_auths = collection_prototype_auth.find(_type: 'ObjectAuth', obj_authable_id: category['_id'], '$or' => [{privilege_user_ids: {'$not' => {'$size' => 0}}}, {role_ids: {'$not' => {'$size' => 0}}}, {sub_role_ids: {'$not' => {'$size' => 0}}}]).entries
          if object_auths.present?
            object_auths.each do |object_auth|
              if object_auth['title'].eql?('fact_check')
                authorization = new_category.auth_approval || new_category.create_auth_approval(module_app_id: module_app.id, title: "category_approval_#{module_app.key}")   
              else
                authorization = new_category.auth_sub_manager || new_category.create_auth_sub_manager(module_app_id: module_app.id, title: "category_authorization_#{module_app.key}")
              end
              add_users(object_auth, authorization)
              collection_prototype_auth.remove(object_auth)
            end
          end

        end

      end
    end

    #del db table
    collection_category.drop
    old_collection_db.drop
    old_image_collection_db.drop

  end 


end