module RepositoriesHelper
  def render_permission(user, project)
    return "Admin" if user&.admin?
    project.get_premission(user)
  end

  def render_decode64_content(str)
    return nil if str.blank?
    Base64.decode64(str).force_encoding("UTF-8").encode("UTF-8", invalid: :replace)
  end

  def download_type(str)
    default_type = %w(ppt pptx pdf zip 7z rar exe pdb obj idb RData rdata doc docx mpp vsdx dot otf eot ttf woff woff2 mp4 mov wmv flv mpeg avi avchd webm mkv apk xlsx xls)
    default_type.include?(str&.downcase) || str.blank?
  end

  def image_type?(str)
    default_type = %w(png jpg gif tif psd svg bmp webp jpeg ico psd)
    default_type.include?(str.to_s.gsub("\r", "").downcase)
  end

  def is_text_file?(entry)
    entry['is_text_file']
  end

  def is_readme?(type, str)
    return false if type != 'file' || str.blank?
    readme_types = ["readme.md", "readme", "readme_en.md", "readme_zh.md", "readme_en", "readme_zh"]
    readme_types.include?(str.to_s.downcase) || str =~ CustomRegexp::MD_REGEX
  end

  def render_commit_author(author_json)
    return nil if author_json.blank? || (author_json["id"].blank? && author_json['name'].blank?)
    if author_json["id"].present?
      return find_user_by_gitea_uid author_json['id']
    end
    if author_json["id"].nil? && (author_json["name"].present? && author_json["email"].present?)
      return find_user_by_login_and_mail(author_json['name'], author_json["email"])
    end
  end

  def render_cache_commit_author(author_json)
    user = nil
    if author_json["name"].present? && author_json["email"].present?
      user = find_user_in_redis_cache(author_json['name'], author_json['email'])
    end
    if author_json["Name"].present? && author_json["Email"].present?
      user = find_user_in_redis_cache(author_json['Name'], author_json['Email'])
    end
    if user.blank? && author_json["email"].present?
      user = User.find_by(mail: author_json["email"])
    end
    if user.blank? && author_json["Email"].present?
      user = User.find_by(mail: author_json["Email"])
    end
    user
  end

  def readme_render_decode64_content(str, owner, repo, ref, path)
    return nil if str.blank?
    begin
      content = Base64.decode64(content).force_encoding('UTF-8').valid_encoding? ? Base64.decode64(str).force_encoding('UTF-8') : Base64.decode64(str).force_encoding("GBK").encode("UTF-8")

      c_regex = /\!\[.*?\]\((.*?)\)/
      src_regex = /src=\"(.*?)\"/
      src2_regex = /src='(.*?)'/
      ss = content.to_s.scan(c_regex)
      ss_src = content.scan(src_regex)
      ss_src2 = content.scan(src2_regex)
      total_images = ss + ss_src + ss_src2
      if total_images.length > 0
        total_images.each do |s|
          begin
            image_title = /\"(.*?)\"/
            r_content = s[0]
            remove_title = r_content.to_s.scan(image_title)
            # if remove_title.length > 0
            #   r_content = r_content.gsub(/#{remove_title[0]}/, "").strip
            # end
            path_last = r_content
            path_current = ""
            # 相对路径处理
            if r_content.start_with?("../")
              relative_path_length = r_content.split("../").size - 1
              path_pre = path.split("/").size - 1 - relative_path_length
              path_pre = 0 if path_pre < 0
              path_current = path_pre == 0 ? "" : path.split("/")[0..path_pre].join("/")
              path_last =  r_content.split("../").last
            elsif r_content.start_with?("/")  # 根路径处理
              path_last = r_content[1..r_content.size]
            else
              path_current = path
            end
            # if r_content.include?("?")
            #   new_r_content = r_content + "&raw=true"
            # else
            #   new_r_content = r_content + "?raw=true"
            # end
            new_r_content = r_content

            unless r_content.include?("http://") || r_content.include?("https://") || r_content.include?("mailto:")
              # new_r_content = "#{path}" + new_r_content
              new_r_content = [base_url, "/api/#{owner&.login}/#{repo.identifier}/raw/#{path_current}/#{path_last}?ref=#{ref}"].join
            end
            content = content.gsub(/src=\"#{r_content}\"/, "src=\"#{new_r_content}\"").gsub(/src='#{r_content}'/, "src=\"#{new_r_content}\"")
          rescue
            next
          end
        end
      end
  
      return content
    rescue
      return str
    end
  end

   # author hui.he
   def new_readme_render_decode64_content(str, owner, repo, ref, readme_path, readme_name)
    file_path = readme_path.include?('/') ? readme_path.gsub("/#{readme_name}", '') : readme_path.gsub("#{readme_name}", '')
    return nil if str.blank?
    content = Base64.decode64(str).force_encoding('UTF-8').valid_encoding? ? Base64.decode64(str).force_encoding('UTF-8') : Base64.decode64(str).force_encoding("GBK").encode("UTF-8")
    # s_regex = /\s\!\[.*?\]\((.*?)\)\s/
    s_regex_c = /`{1,2}[^`](.*?)`{1,2}/
    s_regex = /```([\s\S]*?)```[\s]?/
    s_regex_1 = /\[.*?\]\((.*?)\)/
    # 变量图片相对路径
    s_regex_2 = /\[.*?\]:(.*?)\n/
    src_regex = /src=\"(.*?)\"/
    src_regex_1 = /src=\'(.*?)\'/
    src_regex_2 = /src = (.*?) /
    src_regex_3 = /src= (.*?) /
    src_regex_4 = /src =(.*?) /
    src_regex_5 = /src =(.*?) /
    href_regex = /href=\"(.*?)\"/
    href_regex_1 = /href=\'(.*?)\'/
    ss_c = content.to_s.scan(s_regex_c)
    ss = content.to_s.scan(s_regex)
    ss_1 = content.to_s.scan(s_regex_1)
    ss_2 = content.to_s.scan(s_regex_2)
    ss_src = content.to_s.scan(src_regex)
    ss_src_1 = content.to_s.scan(src_regex_1)
    ss_src_2 = content.to_s.scan(src_regex_2)
    ss_src_3 = content.to_s.scan(src_regex_3)
    ss_src_4 = content.to_s.scan(src_regex_4)
    ss_src_5 = content.to_s.scan(src_regex_5)
    ss_href = content.to_s.scan(href_regex)
    ss_href_1 = content.to_s.scan(href_regex_1)
    total_sources = {ss_c: ss_c,ss: ss, ss_1: ss_1, ss_2: ss_2, ss_src: ss_src, ss_src_1: ss_src_1, ss_src_2: ss_src_2, ss_src_3: ss_src_3, ss_src_4: ss_src_4, ss_src_5: ss_src_5, ss_href: ss_href, ss_href_1: ss_href_1}
    puts total_sources
    # total_sources.uniq! 
    total_sources.except(:ss, :ss_c).each do |k, sources|
      sources.each do |s|
        begin
          s_content = s[0]
          # 链接直接跳过不做替换
          next if s_content.starts_with?('http://') || s_content.starts_with?('https://') || s_content.starts_with?('mailto:') || s_content.blank?
          ext = File.extname(s_content)[1..-1]
          ext = ext.split("?")[0] if ext.include?("?")
          ext = ext.gsub(/ \".*\"/, "") if ext.include?(" ")
          if (image_type?(ext) || download_type(ext)) && !ext.blank?
            s_content = s_content.starts_with?("/") ? s_content[1..-1] : s_content[0..-1]
            s_content = File.expand_path(s_content, file_path)
            s_content = s_content.split("#{Rails.root}/")[1]
            s_content = s_content.gsub(/ \".*\"/, "") if s_content.include?(" ")
            next if s_content.blank?
            # content = content.gsub(s[0], "/#{s_content}")
            join_xxx = s_content.include?("?") ? "&" : "?"
            s_content = [base_url, "/api/#{owner&.login}/#{repo.identifier}/raw/#{s_content}#{join_xxx}ref=#{ref}"].join
            case k.to_s
            when 'ss_src'
              content = content.gsub("src=\"#{s[0]}\"", "src=\"#{s_content}\"")
            when 'ss_src_1'
              content = content.gsub("src=\'#{s[0]}\'", "src=\'#{s_content}\'")
            when 'ss_src_2'
              content = content.gsub("src = #{s[0]}", "src=\'#{s_content}\'")
            when 'ss_src_3'
              content = content.gsub("src= #{s[0]}", "src=\'#{s_content}\'")
            when 'ss_src_4'
              content = content.gsub("src =#{s[0]}", "src=\'#{s_content}\'")
            when 'ss_src_5'
              content = content.gsub("src=#{s[0]}", "src=\'#{s_content}\'")
            when 'ss_2'
              content = content.gsub(/]:#{s[0]}/, "]: #{s_content.to_s.gsub(" ","").gsub("\r", "")}")
            when 'ss_href'
              content = content.gsub("href=\"#{s[0]}\"", "href=\"#{s_content}\"")
            when 'ss_href_1'
              content = content.gsub("href=\'#{s[0]}\'", "href=\'#{s_content}\'")
            else
              ## md中图片处理包含中文名称，tip
              if s[0].to_s.include?(" ")
                s1 = s[0].to_s.split(" ")
                str1 = s1[0]
                str2 = s1[1] if s1.size >1
                content = content.gsub("(#{str1} #{str2})", "(#{s_content} #{str2})")
              else
                content = content.gsub("(#{s[0]})", "(#{s_content})")
              end
            end
          else
            path = [owner&.login, repo&.identifier, 'tree', ref, file_path].join("/")
            s_content = File.expand_path(s_content, path)
            s_content = s_content.split("#{Rails.root}")[1]
            next if s_content.blank?
            case k.to_s
            when 'ss_src'
              content = content.gsub("src=\"#{s[0]}\"", "src=\"/#{s_content}\"")
            when 'ss_src_1'
              content = content.gsub("src=\'#{s[0]}\'", "src=\'/#{s_content}\'")
            when 'ss_2'
              content = content.gsub(/]:#{s[0]}/, "]: /#{s_content.to_s.gsub(" ","").gsub("\r", "")}")
            when 'ss_href'
              content = content.gsub("href=\"#{s[0]}\"", "href=\"#{s_content}\"")
            when 'ss_href_1'
              content = content.gsub("href=\'#{s[0]}\'", "href=\'#{s_content}\'")
            else
              content = content.gsub("(#{s[0]})", "(#{s_content})")
            end
          end
        rescue
          next
        end
      end
    end

    after_ss_souces = content.to_s.scan(s_regex)
    after_ss_souces.each_with_index do |s, index|
      next if total_sources[:ss][index].nil?
      content = content.gsub("#{s[0]}","#{total_sources[:ss][index][0]}")
    end
    after_ss_c_souces = content.to_s.scan(s_regex_c)
    after_ss_c_souces.each_with_index do |s, index|
      next if total_sources[:ss_c][index].nil?
      content = content.gsub("#{s[0]}","#{total_sources[:ss_c][index][0]}")
    end
    return content
  rescue Exception => e
    Rails.logger.error("===================#{readme_path}:#{readme_name}:error:#{e}")
    # e.backtrace.each { |msg| Rails.logger.error(msg) }
    return str
  end

  # unix_time values for example: 1604382982
  def render_format_time_with_unix(unix_time)
    Time.at(unix_time).strftime("%Y-%m-%d %H:%M")
  end

  # date for example: 2020-11-01T19:57:27+08:00
  def render_format_time_with_date(date)
    date.to_time.strftime("%Y-%m-%d %H:%M")
  end

  def readme_decode64_content(entry, owner, repo, ref, path=nil)
    Rails.logger.info("entry===#{entry["type"]} #{entry["name"]}")
    content = entry['content'].present? ? entry['content'] : Gitea::Repository::Entries::GetService.call(owner, repo.identifier, URI.escape(entry['path']), ref: ref)['content']
    # readme_render_decode64_content(content, owner, repo, ref)
    text = new_readme_render_decode64_content(content, owner, repo, ref, entry['path'], entry['name'])
    # text = "该内容不合规，请修改。" if text.present? && !HarmoniousDictionary.clean?(text)
    text
  end

  def decode64_content(entry, owner, repo, ref, path=nil)
    if is_readme?(entry['type'], entry['name'])
      Rails.logger.info("entry===#{entry["type"]} #{entry["name"]}")
      content = entry['content'].present? ? entry['content'] : Gitea::Repository::Entries::GetService.call(owner, repo.identifier, URI.escape(entry['path']), ref: ref)['content']
      # Rails.logger.info("content===#{content}")
      return Base64.decode64(content).force_encoding("GBK").encode("UTF-8") unless Base64.decode64(content).force_encoding('UTF-8').valid_encoding?
      text = Base64.decode64(content).force_encoding('UTF-8')
      # text = "该内容不合规，请修改。" if text.present? && !HarmoniousDictionary.clean?(text)
      text
    elsif entry['is_text_file'] == true
      text = render_decode64_content(entry['content'])
      # text = "该内容不合规，请修改。" if text.present? && !HarmoniousDictionary.clean?(text)
      text
    else
      file_type = File.extname(entry['name'].to_s)[1..-1]
      if image_type?(file_type)
        return entry['content'].nil? ? Gitea::Repository::Entries::GetService.call(owner, repo.identifier, URI.escape(entry['path']), ref: ref)['content'] : entry['content']  
      end
      if download_type(file_type)
        return entry['content']
      end
      text = render_decode64_content(entry['content'])
      # text = "该内容不合规，请修改。" if text.present? && !HarmoniousDictionary.clean?(text)
      text
    end
  end

  def base64_to_image(path, content)
    # generate to https://git.trusite.net/pawm36ozq/-/raw/branch/master/entrn.png"
    content      = Base64.decode64(content)
    File.open(path, 'wb') { |f| f.write(content) }
  end
  
  def render_download_image_url(dir_path, file_path, content)
    full_path = file_path.starts_with?("/") ? [dir_path, file_path].join("") : [dir_path, file_path].join("/")
    file_name = full_path.split("/")[-1]
    # 用户名/项目标识/文件路径
    dir_path = generate_dir_path(full_path.split("/"+file_name)[0])

    file_path = [dir_path, file_name].join('/')

    puts "##### render_download_image_url file_path: #{file_path}"
    base64_to_image(file_path, content)
    file_path = file_path[6..-1]
    File.join(base_url, file_path)
  end
  
  def generate_dir_path(dir_path)
    # tmp_dir_path
    # eg: jasder/forgeplus/raw/branch/ref
    dir_path = ["public", tmp_dir, dir_path].join('/')
    puts "#### dir_path: #{dir_path}"
    unless Dir.exists?(dir_path)
      FileUtils.mkdir_p(dir_path) ##不成功这里会抛异常
    end
    dir_path
  end

  def tmp_dir
    "repo"
  end

  def repo_git_submodule_url(owner, repo, path)
    unless (path.starts_with?('http://') || path.starts_with?('https://'))
      path = File.expand_path(path, "/#{owner&.login}/#{repo&.identifier}")
    end

    return path
  end
end
