# encoding: utf-8

require 'redmine/scm/adapters/git_adapter'

module EasyPatch
  module ScmGitAdapterPatch

    def self.included(base)
      base.extend(ClassMethods)
      base.send(:include, InstanceMethods)

      base.class_eval do

        alias_method_chain :git_cmd, :easy_extensions
        alias_method_chain :revisions, :easy_extensions

        def changeset_branches(scmid)
          branches = []
          cmd_args = %w|branch --no-color --no-abbrev --contains| << scmid
          git_cmd(cmd_args) do |io|
            io.each_line do |line|
              branch_rev = line.match('\s*(\*?)\s*(.*?)$')
              name = branch_rev[2]
              if name.present?
                name.force_encoding(@path_encoding)
                branches << name.strip
              end
            end
          end
          branches.sort!
          branches
        rescue Redmine::Scm::Adapters::AbstractAdapter::ScmCommandAborted
          []
        end

        def ensure!(repo_url)
          FileUtils.mkdir(repo_container_dir) unless repo_container_dir.exist?

          repository_url = repo_container_dir.join(File.basename(repo_url))

          Dir.chdir(repo_container_dir) { system("git clone --mirror \"#{repo_url}\"") } unless repository_url.exist?

          return repository_url
        end

        def destroy(repository)
          FileUtils.rm_rf repository.root_url
        end

        private

        def repo_container_dir
          Rails.root.join(EasySetting.value('git_repository_path'))
        end

      end
    end

    module InstanceMethods

      def git_cmd_with_easy_extensions(args, options = {}, &block)
        repo_path = root_url || url
        if File.exist?(repo_path)
          git_cmd_without_easy_extensions(args, options, &block)
        end
      end

      def revisions_with_easy_extensions(path, identifier_from, identifier_to, options={})
        revs = revisions_without_easy_extensions(path, identifier_from, identifier_to, options)
        revs.each {|rev| puts rev.message = rev.message.force_encoding('UTF-8') }
        revs
      end

    end

    module ClassMethods
    end

  end
end
EasyExtensions::PatchManager.register_other_patch 'Redmine::Scm::Adapters::GitAdapter', 'EasyPatch::ScmGitAdapterPatch'
