# frozen_string_literal: true #-- # wwwjdic # rubocop:disable Style/AsciiComments # © 2014 Marco Bresciani # rubocop:enable Style/AsciiComments # # This file is part of wwwjdic. # # wwwjdic is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation, either version 3 of the License, or (at your # option) any later version. # # wwwjdic is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # for more details. # # You should have received a copy of the GNU General Public License # along with wwwjdic. If not, see . # # SPDX-FileCopyrightText: 2014 Marco Bresciani # # SPDX-License-Identifier: GPL-3.0-or-later #++ require 'i18n' require 'json' require_relative '../constants' module WWWJDic # This class is a simple API to interact with WWWJDic Backboor # Entry/API. # Author:: {Marco Bresciani}[mailto:marcobresciani_1974@libero.it] # Copyright:: (C) 2014 Marco Bresciani # License:: GNU General Public License version 3 class Splitter # Creates a +Splitter+ object. # # Usage:: new_splitter = Splitter.new translation_content # Returns:: a +Splitter+ object. def initialize(translation) @translation = translation.force_encoding('UTF-8') end def title Regexp.last_match(1) if %r{(.*)}.match @translation end def translation Regexp.last_match(1).strip if %r{
(.*)
}m.match @translation end def message return Regexp.last_match(1).strip unless @translation.nil? || !/

(.*)

/m.match(@translation) Regexp.last_match(1) if @translation.nil? && /

(.*)

/m.match(@translation)
    end

    def lines
      result = []
      translation.each_line do |a_line|
        stripped_line = a_line.strip
        result.push stripped_line unless stripped_line.empty?
      end
      result unless result.empty?
    end

    # @return [Array] the arrays of elements containing the answer
    def content
      result = []
      lines.each do |a_line|
        inner = {}
        fill_inner_data(a_line, inner)
        inner[:meanings] = inner[:text].split('/') if inner[:text].include? '/'
        result.push inner unless inner.empty?
      end

      result unless result.empty?
    end

    private

    def fill_inner_data(a_line, inner)
      if /(.*)\[/m.match a_line
        inner[:word] = Regexp.last_match(1).strip
        inner[:kana] = Regexp.last_match(1).strip if /\[(.*)\]/m.match a_line
        inner[:text] = Regexp.last_match(1).strip if %r{\] /(.*)/}m.match a_line
      else
        inner[:kana] = Regexp.last_match(1).strip if %r{^(.*)(\s)/}m.match a_line
        inner[:word] = inner[:kana]
        inner[:text] = Regexp.last_match(1).strip if %r{/(.*)/}m.match a_line
      end
    end
  end
end