# Gitlab5.3 API操作接口
# Add by nwb
# 暂时没支持SSH
# 接口通过HTTP协议与服务器交互，理论上只要能安装gitlab的操作系统本接口都能支持
# 本机的测试环境是Ubuntu 12.04

module GitlabHelper

  # gitlab版本库数据本地保存的根目录
  ROOT_PATH="/home/git/repositories/"
  PROJECT_PATH_CUT =  40
  # gitlab版本库所在服务器
  # 注意REPO_IP_ADDRESS必须以http://开头，暂时只支持HTTP协议，未支持SSH
  #REPO_IP_ADDRESS = "http://" + Setting.host_repository
  REPO_IP_ADDRESS = "http://192.168.137.100"
  GITLAB_API = "/api/v3"

  # 用户在项目中的权限级别
  GUEST     = 10
  REPORTER  = 20
  DEVELOPER = 30
  MASTER    = 40

  # gitlab的登录验证信息
  # add by nwb
  def self.gitlab_token=(token)
    Thread.current[:gitlab_token] = token
  end

  # gitlab的登录验证信息
  # add by nwb
  def self.gitlab_token
    Thread.current[:gitlab_token] ||= nil
  end

  # 登录gitlab
  # add by nwb
  def login_gitlab(email,password)
    url =  REPO_IP_ADDRESS +  GITLAB_API + "/session"
    uri = URI.parse(url)
    data = {email:email, password:password}
    begin
    res = Net::HTTP.post_form(uri, data)
    if res.code == '201'
      temp = ActiveSupport::JSON.decode(res.body)
      GitlabHelper.gitlab_token= temp['private_token']
      return true
    else
      return false
    end
    rescue =>err
      return false
    end
  end

  # 创建项目
  # add by nwb
  def create_project(project_name)
    url =  REPO_IP_ADDRESS +  GITLAB_API + "/projects"
    uri = URI.parse(url)
    data = {name:project_name, private_token:GitlabHelper.gitlab_token}
    begin
      res = Net::HTTP.post_form(uri, data)
      if res.code == '201'
        temp = ActiveSupport::JSON.decode(res.body)
        #新创建项目的版本库地址
        respo = temp['http_url_to_repo']
        respo['http://localhost'] =  REPO_IP_ADDRESS
        # 新创建项目的web地址
        webaddress = temp['web_url']
        webaddress['http://localhost'] =  REPO_IP_ADDRESS
        return true
      else
        return false
      end
    rescue =>err
      return false
    end
  end

  # 为指定用户创建版本库
  # project_name：版本库名称 user_id:Gitlab版本库中的用户编号
  # add by nwb
  def create_project_for_user(project_name,user_id)
    url =  REPO_IP_ADDRESS +  GITLAB_API + "/projects/user/"  + user_id
    uri = URI.parse(url)
    data = {user_id:user_id, name:project_name,private_token:GitlabHelper.gitlab_token}
    begin
      res = Net::HTTP.post_form(uri, data)
      if res.code == '201'
        temp = ActiveSupport::JSON.decode(res.body)
        #新创建项目的版本库地址
        respo = temp['http_url_to_repo']
        respo['http://localhost'] =  REPO_IP_ADDRESS
        # 新创建项目的web地址
        webaddress = temp['web_url']
        webaddress['http://localhost'] =  REPO_IP_ADDRESS
        return true
      else
        return false
      end
    rescue =>err
      return false
    end
  end

  # 创建用户
  # loginname：登录名称(版本库路径包含)  name：用户姓名
  # add by nwb
  def create_user (loginname,name,password,email)
    url =  REPO_IP_ADDRESS +  GITLAB_API + "/users"
    uri = URI.parse(url)
    data = {email:email,password:password,username:loginname, name:name, private_token:GitlabHelper.gitlab_token}
    begin
      res = Net::HTTP.post_form(uri, data)
      if res.code == '201'
        temp = ActiveSupport::JSON.decode(res.body)
        #新创建的gitlab用户编号(需保存)
        user_id = temp['id']
        return true
      else
        return false
      end
    rescue =>err
      return false
    end
  end

  # 删除用户
  #  user_id:用户在gitlab中的id
  # add by nwb
  def delete_user(user_id)
    url =  REPO_IP_ADDRESS +  GITLAB_API + "/users/" + user_id
    uri = URI.parse(url)
    data = {id:user_id,private_token:GitlabHelper.gitlab_token}
    http = Net::HTTP.new uri.host, uri.port
    begin
      req = Net::HTTP::Delete.new(uri.request_uri)
      req.form_data = data
      res= http.start { |http| http.request req }
      if res.code == '200'
        temp = ActiveSupport::JSON.decode(res.body)
        # 删除成功，对应更新trustie用户的gitlab用户编号
        return true
      else
        return false
      end
    rescue =>err
      return false
    end
  end

  # 给用户添加一个可操作的项目
  # 若用户已在该项目中，权限级别取新权限与现有权限的最大值
  # project_id:项目在gitlab中的id user_id:用户在gitlab中的id
  # access_level为用户在项目中的权限级别，对应如下：
  #GUEST     = 10
  #REPORTER  = 20
  #DEVELOPER = 30
  #MASTER    = 40
  # add by nwb
  def add_user_to_project(project_id,user_id,access_level)
    url =  REPO_IP_ADDRESS +  GITLAB_API + "/projects/" + project_id +"/members"
    uri = URI.parse(url)
    data = {id:project_id,user_id:user_id,access_level:access_level, private_token:GitlabHelper.gitlab_token}
    begin
      res = Net::HTTP.post_form(uri, data)
      if res.code == '201'
        temp = ActiveSupport::JSON.decode(res.body)
        return true
      else
        return false
      end
    rescue =>err
      return false
    end
  end

  # 从项目中删除用户
  # project_id:项目在gitlab中的ids user_id:用户在gitlab中的id
  # add by nwb
  def delete_user_from_project(project_id,user_id)
    url =  REPO_IP_ADDRESS +  GITLAB_API + "/projects/" + project_id +"/members/" + user_id
    uri = URI.parse(url)
    data = {id:project_id,user_id:user_id,private_token:GitlabHelper.gitlab_token}
    http = Net::HTTP.new uri.host, uri.port
    begin
      req = Net::HTTP::Delete.new(uri.request_uri)
      req.form_data = data
      res= http.start { |http| http.request req }
      if res.code == '200'
        temp = ActiveSupport::JSON.decode(res.body)
        return true
      else
        return false
      end
    rescue =>err
      return false
    end
  end

  # 发送post消息
  # add by nwb
  def post(url, params)
    uri = URI.parse(url)
    http = Net::HTTP.new(uri.host, uri.port)
    if uri.scheme == 'https'
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      http.use_ssl = true
    end
    begin
      request = Net::HTTP::Post.new(uri.request_uri)
      request['Content-Type'] = 'application/json;charset=utf-8'
      request['User-Agent'] = 'Mozilla/5.0 (Windows NT 5.1; rv:29.0) Gecko/20100101 Firefox/29.0'
      request['X-ACL-TOKEN'] = 'xxx_token'
      #request.set_form_data(params)
      request.body = params.to_json
      response = http.start { |http| http.request(request) }
      return JSON.parse response.body
    rescue =>err
      return nil
    end
  end

  # 发送get消息
  # add by nwb
  def get(url, params)
    uri = URI.parse(url)
    uri.query = URI.encode_www_form(params)
    http = Net::HTTP.new uri.host, uri.port
    if uri.scheme == 'https'
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      http.use_ssl = true
    end
    begin
      request = Net::HTTP::Get.new uri.request_uri
      request['Content-Type'] = 'application/json;charset=utf-8'
      request['User-Agent'] = 'Mozilla/5.0 (Windows NT 5.1; rv:29.0) Gecko/20100101 Firefox/29.0'
      request['X-ACL-TOKEN'] =  'xxx_token'
      response = http.start { |http| http.request request }
      return JSON.parse response.body
    rescue =>err
      return nil
    end
  end

end