# frozen_string_literal: true

module LostInTranslation
  def self.split_file
    @master, @slave, paths = init(false)

    prepare_for_edit(master: @master[:path])
    prepare_paths([paths[:master]])

    master_file = YAML.load_file(paths[:master])[@master[:lang]]

    count = master_file.select { |_k, v| v.is_a?(Hash) }.size
    new_hash = {}

    if ask_for_split(@master[:lang], count)
      master_file.each_pair do |key, value|
        next unless value.is_a?(Hash)
        new_hash[@master[:lang]] = { key => value }
        File.open(paths[:slave], 'w') { |file| file.write(new_hash.to_yaml(line_width: -1)) }
        postpare_paths([paths[:slave]])
        root_path = @master[:path].split('/').reverse.drop(1).reverse.join('/')
        filename = @master[:path].split('/').last
        FileUtils.cp(paths[:slave], "#{root_path}/#{key}.#{filename}")
        master_file.delete(key)
      end

      new_hash[@master[:lang]] = master_file
      File.open(paths[:master], 'w') { |file| file.write(new_hash.to_yaml(line_width: -1)) }
      postpare_paths([paths[:master]])
      FileUtils.cp(paths[:master], @master[:path])
    end

    reset_tmp_files
    log 'Done'
    log
  end
end
