from resources.common_imports import *

#les variables globales minimum
from resources.config import mattermost_user, mattermost_pass, mattermost_url

# on utilise mmctl et pas l'apiv4 de MM
# pourquoi ? passe que mmctl déjà utilisé dans les scripts kaz. 

#*************************************************

def Mattermost_authenticate():
     # Authentification sur MM
     global mattermost_url, mattermost_user, mattermost_pass
     cmd = f"/mm/mmctl auth login {mattermost_url} --name local-server --username {mattermost_user} --password {mattermost_pass}"
     subprocess.run(cmd, shell=True, stderr=subprocess.STDOUT, check=True)

#*************************************************

class Mattermost_message(Resource):

    @jwt_required()
    def post(self,message,equipe="kaz",canal="creation-comptes"):
        """
        Envoyer un message dans une Equipe/Canal de MM
        ---
        tags:
          - Mattermost        
        security:
          - Bearer: []                
        parameters:
          - in: path
            name: equipe
            type: string
            required: true
          - in: path
            name: canal
            type: string
            required: true
          - in: path
            name: message
            type: string
            required: true
        
        responses:
            200:
                description: Affiche un message dans un canal d'une équipe
            500:
                description: oops
        """    
        Mattermost_authenticate()
    
        try:
            cmd="/mm/mmctl post create "+equipe+":"+canal+" --message "+ "\"" + message + "\""
            output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
            return "Message envoyé", 200
        except subprocess.CalledProcessError:
            return "Message non envoyé", 500


#*************************************************

class Mattermost_user(Resource):
  
    def __init__(self):
      Mattermost_authenticate()
  
#*************************************************  
    @jwt_required()
    def get(self,user):
        """
        Le user existe t-il sur MM ? 
        ---
        tags:
          - Mattermost User
        security:
          - Bearer: []                
        parameters: 
          - in: path
            name: user
            type: string
            required: true        
            description: possible d'entrer un username, un email
        responses:
            200:
                description: Existe
            404:
                description: N'existe pas
        """    
            
        try:
            cmd = f"/mm/mmctl user search {user} --json"
            user_list_output = subprocess.check_output(cmd, shell=True)
            return 200  # Le nom d'utilisateur existe
        except subprocess.CalledProcessError:
            return 404  # Le nom d'utilisateur n'existe pas

#*************************************************
    @jwt_required()
    def post(self,user,email,password):
        """
        Créer un utilisateur sur MM
        ---
        tags:
          - Mattermost User
        security:
          - Bearer: []                
        parameters: 
          - in: path
            name: user
            type: string
            required: true        
          - in: path
            name: email
            type: string
            required: true        
          - in: path
            name: password
            type: string
            required: true        
        responses:
            200:
                description: Utilisateur créé
            400:
                description: oops, Utilisateur non créé
        """        
        
       # Création de l'utilisateur
        try:
            cmd = f"/mm/mmctl user create --email {email} --username {user} --password {password}"
            output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
            return output.decode("utf-8"), 200

        except subprocess.CalledProcessError as e:
            return e.output.decode("utf-8"), 400

#*************************************************

    @jwt_required()
    def delete(self,email):
        """
        Supprimer un utilisateur sur MM
        ---
        tags:
          - Mattermost User
        security:
          - Bearer: []                
        parameters: 
          - in: path
            name: email
            type: string
            required: true        
        responses:
            200:
                description: Utilisateur supprimé
            400:
                description: oops, Utilisateur non supprimé
        """        
        
        try:
            cmd = f"/mm/mmctl user delete {email} --confirm"
            output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
            return output.decode("utf-8"), 200

        except subprocess.CalledProcessError as e:
            return e.output.decode("utf-8"), 400

#*************************************************

    @jwt_required()
    def put(self,email,new_password):
        """
        Changer un password pour un utilisateur de MM
        ---
        tags:
          - Mattermost User
        security:
          - Bearer: []                
        parameters: 
          - in: path
            name: email
            type: string
            required: true        
          - in: path
            name: new_password
            type: string
            required: true        
        responses:
            200:
                description: Mot de passe de l'Utilisateur changé
            400:
                description: oops, Mot de passe de l'Utilisateur inchangé
        """        
        try:
            cmd = f"/mm/mmctl user change-password {email} --password {new_password}"
            output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
            return output.decode("utf-8"), 200 

        except subprocess.CalledProcessError as e:
            return e.output.decode("utf-8"), 400

#*************************************************
        

#*************************************************

class Mattermost_user_team(Resource):
  
    @jwt_required()
    def post(self,email,equipe):
        """
        Affecte un utilisateur à une équipe MM
        ---
        tags:
          - Mattermost Team       
        security:
          - Bearer: []        
        parameters: 
          - in: path
            name: email
            type: string
            required: true        
          - in: path
            name: equipe
            type: string
            required: true        
        responses:
            200:
                description: l'utilisateur a bien été affecté à l'équipe
            400:
                description: oops, Utilisateur non affecté
        """
        Mattermost_authenticate()
        
        try:
            cmd = f"/mm/mmctl team users add {equipe} {email}"
            output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
            return output.decode("utf-8"), 200 

        except subprocess.CalledProcessError as e:
            return e.output.decode("utf-8"), 400 


#*************************************************

class Mattermost_user_channel(Resource):
    @jwt_required()
    def post(self,email,equipe,canal):
        """
        Affecte un utilisateur à un canal MM
        ---
        tags:
          - Mattermost        
        security:
          - Bearer: []                
        parameters: 
          - in: path
            name: email
            type: string
            required: true        
          - in: path
            name: equipe
            type: string
            required: true                
          - in: path
            name: canal
            type: string
            required: true        
        responses:
            200:
                description: l'utilisateur a bien été affecté au canal
            400:
                description: oops, Utilisateur non affecté
        """
        Mattermost_authenticate()
        
        try:
            cmd = f'/mm/mmctl channel users add {equipe}:{canal} {email}'
            output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
            return output.decode("utf-8"), 200

        except subprocess.CalledProcessError as e:
            return e.output.decode("utf-8"), 400


#*************************************************

class Mattermost_team(Resource):
  
    def __init__(self):
      Mattermost_authenticate()
      
#*************************************************  

    @jwt_required()
    def get(self):
        """
        Lister les équipes sur MM 
        ---
        tags:
          - Mattermost Team   
        security:
          - Bearer: []                
        parameters: []
        responses:
            200:
                description: liste des équipes
            400:
                description: oops, Equipe non supprimée
        """        
        Mattermost_authenticate()
        
        try:
            cmd = f"/mm/mmctl team list --disable-pager"
            output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)                                    
            data_list = output.decode("utf-8").strip().split('\n')            
            data_list.pop()
            return data_list, 200
            #return jsonify(data_list),200

        except subprocess.CalledProcessError as e:
            return e.output.decode("utf-8"), 400

#*************************************************  
    @jwt_required()
    def post(self,equipe,email):
        """
        Créer une équipe sur MM et affecter un admin si email est renseigné (set admin marche pô)
        ---
        tags:
          - Mattermost Team        
        security:
          - Bearer: []                
        parameters: 
          - in: path
            name: equipe
            type: string
            required: true        
          - in: path
            name: email
            type: string
            required: true
            description: admin de l'équipe
        responses:
            200:
                description: Equipe créée
            400:
                description: oops, Equipe non créée
        """                
        
        try:
            #DANGER: l'option --email ne rend pas le user admin de l'équipe comme c'est indiqué dans la doc :(
            cmd = f"/mm/mmctl team create --name {equipe} --display-name {equipe} --private --email {email}"
            output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
            
            #Workaround: on récup l'id du user et de l'équipe pour affecter le rôle "scheme_admin": true, "scheme_user": true avec l'api MM classique.
            #TODO:
            
            return output.decode("utf-8"), 200

        except subprocess.CalledProcessError as e:
            return e.output.decode("utf-8"), 400
          
#*************************************************
    @jwt_required()
    def delete(self,equipe):
        """
        Supprimer une équipe sur MM 
        ---
        tags:
          - Mattermost Team        
        security:
          - Bearer: []        
        parameters: 
          - in: path
            name: equipe
            type: string
            required: true        
        responses:
            200:
                description: Equipe supprimée
            400:
                description: oops, Equipe non supprimée
        """        
        Mattermost_authenticate()
        
        try:
            cmd = f"/mm/mmctl team delete {equipe} --confirm"
            output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)                        
            return output.decode("utf-8"), 200

        except subprocess.CalledProcessError as e:
            return e.output.decode("utf-8"), 400
          
#*************************************************
