from Model.Object import DataTransferObject as DTO
from Model.Gateway import GatewayConnection as Gateway
import json

class UserGateway(object):

    conn = Gateway.GatewayConnection()

    def getAllUsers(self):
        db = self.conn.getConnection()
        cur = db.cursor()
        cur.execute("SELECT * FROM Users;")
        results = cur.fetchall()
        Users = []
        for user in results:
                Users.append(self.parseToDTO(user))
        return Users

    def addUser(self,newChart):
        c = newChart
        db = self.conn.getSingleton()
        cur = db.cursor()
        sql = """INSERT INTO Users (Name, Description, Server, Query, Dependent, Independent)
                    VALUES (%s, %s, %s, %s, %s, %s)"""
        cur.execute(sql,(c.Name, c.Description, c.Server, c.Query, c.Dependent, c.Independent))
        db.commit()
        return(self.successReturn())

    def modifyUser(self,chart):
        c = chart
        db = self.conn.getConnection()
        cur = db.cursor()
        sql = """UPDATE Users SET Name = %s, Description = %s,
                    Server = %s, Query = %s, Dependent = %s,
                    Independent = %s, WHERE ID = %s"""
        cur.execute(sql,(c.Name, c.Description, c.Server, c.Query, c.Dependent, c.Independent, c.ID))
        db.commit()

    def deleteUser(self,ID):
        db = self.conn.getConnection()
        cur = db.cursor()
        cur.execute("""DELETE FROM Users WHERE ID = %s;""",(str(ID)))
        return(self.successReturn())


    def getUser(self,ID):
        db = self.conn.getSingleton()
        cur = db.cursor()
        cur.execute("""SELECT * FROM Users WHERE ID = %s;""",(str(ID)))
        results = cur.fetchone()
        return self.parseToDTO(results)

    def parseToDTO(self,user):
        UserDTO = DTO.DataTransferObject()
        UserDTO.ID = user[0]
        UserDTO.UserName = user[1]
        UserDTO.FirstName = user[2]
        UserDTO.LastName = user[3]
        UserDTO.Password = user[4]
        return UserDTO

    def successReturn(self):
        result = DTO.DataTransferObject()
        result.Status = str("Good")
        return result

    def failureReturn(self):
        result = DTO.DataTransferObject()
        result.Status = str("Bad")
        return result
