module GithubService
  def github
    Octokit::Client.new access_token: session[:auth_token]
  end

  def gh_repositories
    github.org_repos(organisation_name)
  end

  def gh_teams
    github.org_teams(organisation_name)
  end

  def gh_member_of?(team_name)
    github.team_member?(gh_team_id(team_name), gh_login)
  end

  def gh_login
    github.user.login
  end

  def gh_owner?
    gh_member_of?('Owners')
  end

  def gh_repository(repo_name)
    github.repository(gh_repo_path(repo_name))
  end

  def gh_create_wiki_update_hook(repo_name, url)
    gh_create_hook(repo_name, url, %w(gollum))
  end

  def gh_create_push_hook(repo_name, url)
    gh_create_hook(repo_name, url, %w(push))
  end

  private

  def gh_create_hook(repo_name, url, events)
    github.create_hook(
        gh_repo_path(repo_name),
        'web',
        {url: url, content_type: 'json'},
        {events: events, active: true}
    )
  end

  def gh_repo_path(repo_name)
    "#{organisation_name}/#{repo_name}"
  end

  def gh_team_id(team_name)
    gh_teams.find { |team| team.name == team_name }.try(:id)
  end

  def organisation_name
    ENV['GITHUB_ORGANISATION_NAME']
  end
end
