def __init__(self):
     self.database = Connector().getDatabase()
     self.cursor = self.database.cursor()
class ToolController:
    def __init__(self):
        self.database = Connector().getDatabase()
        self.cursor = self.database.cursor()

    def saveToolToDatabase(self, tool):

        toolDatabaseObject="INSERT INTO TOOLS(NAME,  \
                           OWNER, PRICE_DAY, PRICE_HALF) \
                            VALUES ('%s','%s','%f','%f')"                                                          % \
                           (tool.name,tool.owner,tool.priceDay,tool.priceHalf)
        try:
            self.cursor.execute(toolDatabaseObject)
            self.database.commit()
        except:
            self.database.rollback()
            print("ERROR! while saving a tool to db")

    def deleteToolFromDatabase(self, tool):
        sql = "DELETE FROM TOOLS WHERE NAME = '%s'" % (tool.name)
        try:
            self.cursor.execute(sql)
            self.database.commit()
        except:
            self.database.rollback()
            print("ERROR! while deleting tool")

    def findAllTools(self):
        tools = []
        sql = "SELECT * FROM TOOLS"
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        for row in result:
            from models.ToolModel import Tool
            tool = Tool(row[0], row[1], row[2], row[3])
            tools.append(tool)
        return tools

    def findTool(self, toolName):
        sql = "SELECT * FROM TOOLS WHERE NAME = '%s'" % toolName
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        for row in result:
            from models.ToolModel import Tool
            tool = Tool(row[0], row[1], row[2], row[3])
            tool.description = row[4]
        return tool

    def findAllToolsForUser(self, username):
        sql = "SELECT * FROM TOOLS WHERE OWNER = '%s'" % username
        tools = []
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        for row in result:
            from models.ToolModel import Tool
            tool = Tool(row[0], row[1], row[2], row[3])
            tool.description = row[4]
            tools.append(tool)
        return tools

    def findAllToolsHiredByUser(self, username):
        allDates = CalendarController().getAllColumns()
        toolsHired = []
        for date in allDates:
            sql = "SELECT NAME FROM CALENDAR WHERE `%s` = '%s' OR `%s` = '%s'" % (
                date, username + "_HALF", date, username + "_DAY")
            self.cursor.execute(sql)
            result = self.cursor.fetchall()
            for row in result:
                toolsHired.append(row[0])
        return list(set(toolsHired))

    def getDescriptionForTool(self, toolName):
        sql = "SELECT DESCRIPTION FROM TOOLS WHERE NAME='%s'" % toolName
        self.cursor.execute(sql)
        result = self.cursor.fetchone()
        return str(result[0])

    def setDescriptionForTool(self, toolName, desc):
        sql = """UPDATE TOOLS SET DESCRIPTION='%s' WHERE NAME='%s'""" % (
            desc, toolName)
        self.cursor.execute(sql)
        self.database.commit()
class CalendarController:
    PERIOD = 14

    def __init__(self):
        self.connector = Connector()
        self.database = self.connector.getDatabase()
        self.cursor = self.database.cursor()

    def saveToolCalendar(self, tool):
        sql = "INSERT INTO CALENDAR(NAME) VALUES ('%s')" % \
              (tool)
        try:
            self.cursor.execute(sql)
            self.database.commit()

        except:
            self.database.rollback()

    def addDayToTableCalendar(self, day):
        if (day == self.lastDate()):
            print("DATE ALREADY EXIST")
            return
        elif (day < self.lastDate()):
            print("U CAN NOT GO BACK IN TIME")
            return
        sql = "ALTER TABLE CALENDAR ADD COLUMN \
          `%s` CHAR(20) NOT NULL DEFAULT 'FREE'" % (day)
        try:
            self.cursor.execute(sql)
            self.database.commit()
        except:
            self.database.rollback()

    def getAllColumns(self):
        sql = "DESCRIBE CALENDAR"
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        tab = []
        for row in result:
            tab.append(row[0])
        tab.remove("NAME")
        return tab

    def lastDate(self):
        tab = self.getAllColumns()
        last = tab[len(tab) - 1]
        lastDate = datetime.strptime(last, "%Y-%m-%d").date()
        return lastDate

    def updateCalendar(self):
        tmp = dt.date.today()
        last = self.lastDate()
        dif = (last - tmp).days
        daysToAdd = self.PERIOD - dif - 1
        for i in range(0, daysToAdd):
            self.addDayToTableCalendar(last + timedelta(i + 1))

    def getCalendarForTool(self, tool):
        sql = "SELECT * FROM CALENDAR WHERE NAME = '%s'" % tool.name
        self.cursor.execute(sql)
        result = self.cursor.fetchone()
        types = list(result)
        types.remove(tool.name)
        dates = self.getAllColumns()
        mapList = {}  # DATE : TYPE
        counter = 0
        for i in dates:
            mapList[dates[counter]] = (types[counter])
            counter += 1
        import operator
        return sorted(mapList.items(), key=operator.itemgetter(0))

    def bookToolForDate(self, tool, dateToBook, userName, type="DAY"):
        cal = self.getCalendarForTool(tool)
        #Self made iterator...
        flag = 0
        for i in cal:
            if i[0] == unicode(dateToBook) and i[1] == "FREE":
                flag = 1
                break
        if flag == 1:
            sql = """UPDATE CALENDAR SET `%s` = "%s" WHERE NAME='%s'""" % (
                dateToBook, userName + "_" + type, tool.name)
            self.cursor.execute(sql)
            self.database.commit()
        else:
            print("ERROR")

    def returnTool(self, tool, dateToReturn):
        try:
            sql = """UPDATE CALENDAR SET `%s` = "FREE" WHERE NAME='%s'""" % (
                dateToReturn, tool.name)
            self.cursor.execute(sql)
            self.database.commit()
        except:
            print("ERROR WHILE RETURNING A TOOL")

    def periodTimeCollector(self, dayToAdd=0):
        today = dt.date.today() + timedelta(dayToAdd)
        firstDay = datetime.strptime(self.getAllColumns()[0],
                                     "%Y-%m-%d").date()
        dif = (today - firstDay).days
        if (dif % 30 == 0):
            return True
        return False
class UserController:
    def __init__(self):
        self.database = Connector().getDatabase()
        self.cursor = self.database.cursor()

    def saveUserToDatabase(self, user):

        userDatabaseObject = "INSERT INTO USERS(NAME, PASSWORD) \
           VALUES ('%s', '%s')"                                % \
                             (user.name, user.password)

        try:
            self.cursor.execute(userDatabaseObject)
            self.database.commit()
            print("User {0} saved to database".format(user.name))
            return True

        except:
            self.database.rollback()
            print("ERROR! User {0} NOT saved to database".format(user.name))
            return False

    def deleteUserFromDatabase(self, user):
        sql = "DELETE FROM USERS WHERE NAME = '%s'" % (user.name)
        try:
            self.cursor.execute(sql)
            self.database.commit()
            print("User {0} deleted from database".format(user.name))
        except:
            self.database.rollback()
            print("ERROR! while deleting user")

    def findUser(self, username):
        sql = "SELECT * FROM USERS WHERE NAME = '%s'" % (username)
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        from models.UserModel import User
        user = None
        for row in result:
            name = row[1]
            password = row[2]
            charge = row[3]
            user = User(name, password)
            user.charge = charge
        return user

    def findAllUsers(self):
        users = []
        sql = "SELECT * FROM USERS"
        self.cursor.execute(sql)
        results = self.cursor.fetchall()
        for row in results:
            name = row[1]
            password = row[2]
            charge = row[3]
            from models.UserModel import User
            user = User(name, password)
            user.addCharge(charge)
            users.append(user)
        return users

    def getUserCurrentCharge(self, username):
        sql = "SELECT CHARGE FROM USERS WHERE NAME = '%s'" % username
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        for row in result:
            return row[0]

    def addChargeForUser(self, charge, username):
        old = self.getUserCurrentCharge(username)
        sql = """UPDATE USERS SET CHARGE = %s WHERE NAME='%s'""" % (
            charge + old, username)
        self.cursor.execute(sql)
        self.database.commit()

    def wholeUsersCharge(self):
        if (CalendarController().periodTimeCollector(30)):
            users = self.findAllUsers()
            message = ""
            for user in users:
                message = message + user.name + " current charge is: " + str(
                    user.charge) + "\n"
            return message
        return "THERE MUST BE A MONTH DIF"
class DatabaseCreator:
    PERIOD = 4
    namesUser = ["mati", "filip", "kasia", "wojtek", "sandra"]
    passwords = ["kulis", "mis", "krzys", "tuptus", "kupa"]
    namesTool = ["AA", "BB", "CC", "DD", "EE"]
    priceDay = [10.1, 11.1, 20.5, 30.4, 50.4]
    priceHalf = [2.2, 3.3, 4.4, 5.5, 6.6]

    def __init__(self):
        self.database = Connector().getDatabase()
        self.cursor = self.database.cursor()

    def createTableUsers(self):
        usersTable = """CREATE TABLE USERS (
            ID  INT NOT NULL AUTO_INCREMENT,
           NAME  CHAR(20) NOT NULL UNIQUE,
           PASSWORD CHAR(20) NOT NULL,
           CHARGE FLOAT DEFAULT '0.0',
           PRIMARY KEY(ID)
           )"""
        self.cursor.execute(usersTable)

    def dropTableUsers(self):
        sql = "DROP TABLE IF EXISTS USERS"
        self.cursor.execute(sql)

    def createTableTools(self):
        toolsTable = """CREATE TABLE TOOLS ( 
            NAME  CHAR(20) NOT NULL UNIQUE,
            OWNER  CHAR(20) NOT NULL,
            PRICE_DAY  DOUBLE NOT NULL,
            PRICE_HALF  DOUBLE NOT NULL,
            DESCRIPTION CHAR(100) DEFAULT 'SOME DESCRIPTION'
            )"""
        self.cursor.execute(toolsTable)

    def dropTableTools(self):
        sql = "DROP TABLE IF EXISTS TOOLS"
        self.cursor.execute(sql)

    def createTableCalendar(self):
        calendar = "CREATE TABLE CALENDAR (NAME CHAR(20) NOT NULL UNIQUE"
        for i in range(0, self.PERIOD):
            calendar += ", `%s` CHAR(20) NOT NULL DEFAULT 'FREE' " % (
                dt.date.today() + dt.timedelta(i))
        calendar += ")"
        self.cursor.execute(calendar)

    def dropTableCalendar(self):
        sql = "DROP TABLE IF EXISTS CALENDAR"
        self.cursor.execute(sql)

    def fillTableUsers(self):
        for i in range(len(self.namesUser)):
            sql= "INSERT INTO USERS(NAME, PASSWORD) \
            VALUES ('%s', '%s')"                                 % \
                             (self.namesUser[i], self.passwords[i])
            try:
                self.cursor.execute(sql)
                self.database.commit()
            except:
                self.database.rollback()

    def fillTableTools(self):
        for i in range(len(self.namesUser)):

            sql = "INSERT INTO TOOLS(NAME,  \
                    OWNER, PRICE_DAY, PRICE_HALF) \
                    VALUES ('%s','%s','%f','%f')"                                                  % \
                                 (self.namesTool[i], self.namesUser[i], self.priceDay[i], self.priceHalf[i])
            try:
                self.cursor.execute(sql)
                self.database.commit()
            except:
                self.database.rollback()

    def fillTableCalendar(self):
        for i in range(len(self.namesUser)):

            sql = "INSERT INTO CALENDAR(NAME) VALUES ('%s')" % \
                                 (self.namesTool[i])
            try:
                self.cursor.execute(sql)
                self.database.commit()
            except:
                self.database.rollback()

    def fillPhotos(self):
        pathToSave = os.getcwd() + "/toolsPhotos/"
        pathOfPhotos = os.getcwd() + "/resources/examplePhotosOfTools/"
        if (os.path.exists(pathToSave)):
            shutil.rmtree(pathToSave)
            os.mkdir(pathToSave)
        for i in range(len(self.namesTool)):
            self.tmpPhoto = ImageController().savePhotoOfTool(
                pathOfPhotos + "" + str(i + 1) + ".png", self.namesTool[i])