gemc = Quandl::Utility::Tasks.configuration

task :console do |_t, _args|

require 'pry'
binding.pry

end

namespace gemc.name do

desc "Tag #{gemc.name} with #{gemc.version_with_prefix}"
task :tag do
  fail 'Must be a git repo.' if `git status 2>&1` =~ /Not a git repository/
  version = "#{gemc.tag_prefix}#{File.read('VERSION')}"
  system("git tag -a #{version} -m 'Release #{version}'")
  system('git push --tags')
end

namespace :bump do

  desc "Perform major bump to #{gemc.name}"
  task :major do
    Rake::Task['quandl:bump:perform'].execute(severity: 'major')
  end
  desc "Perform minor bump to #{gemc.name}"
  task :minor do
    Rake::Task['quandl:bump:perform'].execute(severity: 'minor')
  end
  desc "Perform patch bump to #{gemc.name}"
  task :patch do
    Rake::Task['quandl:bump:perform'].execute(severity: 'patch')
  end

end

end

namespace :quandl do

namespace :bump do

  task :perform, :severity do |_t, args|
    # update changelog
    fail 'Must be a git repo.' if `git status 2>&1` =~ /Not a git repository/
    fail 'You have unstaged commits.' if `git status` =~ /Changes not staged for commit/
    Rake::Task['quandl:bump:version'].execute(severity: args[:severity])
    Rake::Task['quandl:changelog:update'].execute
  end

  task :version, :severity do |_t, args|
    severity = args[:severity]
    # extract version info
    major, minor, patch = gemc.version.split('.')
    # bump
    case severity.to_sym
    when :major then
      major = major.to_i + 1
      minor = 0
      patch = 0

    when :minor then
      minor = minor.to_i + 1
      patch = 0

    when :patch then
      patch = patch.to_i + 1
    end
    # commit
    new_version = [major, minor, patch].join('.')
    File.write(gemc.version_path, new_version)
    system("git add #{gemc.version_path}; git commit -m 'Version bump to #{new_version}'")
  end

end

namespace :changelog do
  task :update do |_t, _args|
    # collect commits that match JIRA syntax
    since = gemc.version_with_prefix
    commits = gemc.changelog_matching.map do |matching|
      ` git --no-pager log #{since}..HEAD --pretty=oneline --grep='#{matching}'`
    end.join
    # split newlines and exclude reference, select uniq
    commits = commits.split("\n").map { |c| "* #{c[41..-1]}" }.uniq
    # compose prepend string
    new_version = File.read('VERSION')
    commits = "## #{new_version} \n\n" + commits.join("\n") + "\n\n\n\n"
    # prepend to UPGRADE.md
    changelog = gemc.changelog_path
    puts "Appending commits matching #{gemc.changelog_matching.join(' ')} to #{changelog}\n#{commits}"
    # check for existing changes
    existing_changes = File.exist?(changelog) ? File.read(changelog) : ''
    File.write(changelog, commits + existing_changes)
    system("git add #{changelog}; git commit -m 'Updated changelog with commits from #{new_version}'")
  end
end

end