#coding=utf-8

module Trustie
  module Gitlab
    module Helper
      GUEST     = 10
      REPORTER  = 20
      DEVELOPER = 30
      MASTER    = 40
      OWNER     = 50
      # 项目公开和私有
      PUBLIC = 20
      PRIVATE = 0

      def change_password(uid, en_pwd, salt)
        return unless uid
        options = {:encrypted_password=>en_pwd, :password_salt=>salt}
        self.g.put("/users/ext/#{uid}", :body => options)
        # g.edit_user(uid, :encrypted_password=>en_pwd, :password_salt=>salt)
      end

      def find_user(user)
        us = self.g.get("/users?search=#{user.mail}")
        if Array === us
          us.each do |u|
            return u if u.email == user.mail
          end
        end
        return nil
      end

      def add_user(user)
        u = nil
        begin
          u = find_user(user)
          unless u
            u = self.g.create_user(user.mail,
                                   user.hashed_password,
                                   name: user.show_name,
                                   username: user.login,
                                   confirm: "true")
            user.gid = u.id
            user.save
          end
          if user.gid.nil?
            user.gid = u.id
            user.save
          end
          change_password(u.id, user.hashed_password, user.salt)
        rescue => e
          puts e
        end
        return u
      end

      def del_user(user)
        return unless user.gid
        self.g.delete_user(user.gid)
      end

      def get_gitlab_role m
        case m.roles.first.position
          when 1,2
            GUEST
          when 5
            REPORTER
          when 4
            DEVELOPER
          when 3
            MASTER
          else
            GUEST
        end
      end

    end
  end
end