#coding=utf-8
#
# 
module Trustie
  module Gitlab

    module ManageMember
      attr :g
      include Helper
      def self.included(base)
        base.class_eval {
          before_create :add_gitlab_member
          before_destroy :delete_gitlab_member
          after_save :change_gitlab_member
        }
      end

      def change_gitlab_member
        if isGitlabProject?
          @g ||= ::Gitlab.client
          @g.edit_team_member(project.gpid, self.member.user.gid, self.role.to_gitlab_role )
        end
      end

      def add_gitlab_member
        if isGitlabProject?
          @g ||= ::Gitlab.client
          if self.member.user.gid.nil?
            add_user(self.member.user)
          end
          @g.add_team_member(project.gpid, self.member.user.gid, self.role.to_gitlab_role )
        end
      end

      def delete_gitlab_member
        if isGitlabProject?
          if member.roles.count <=1
              @g ||= ::Gitlab.client
              @g.remove_team_member(project.gpid, self.member.user.gid)
          end
        end
      end

      private
      def project
        self.member.project
      end

      def repository
        unless project.nil?
          project.repository
        end
      end

      def isGitlabProject?
        unless repository.nil?
          repository && repository.gitlab?
        end
      end

    end

  end
end

