#!/usr/bin/env python3

# IB Clearance
# Copyright (C) 2018  Abdulkadir Furkan Şanlı

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sqlite3
import time


def connect_database(file):
    """
    Create and return Connection object
    :param file: database file
    """
    conn = sqlite3.connect(file)
    return conn


def get_lower_weekday():
    """
    Return current weekday's name as lowercase string
    """
    day = time.strftime("%A")
    lower_day = day.lower()
    return lower_day


def check_id(conn, id):
    """
    Return True if existing ID, False is not.
    :param conn: Connection object
    :param id: ID of student, int
    """
    cur = conn.cursor()
    cur.execute("SELECT id FROM students")
    ids = cur.fetchall()

    for x in ids:
        if id == x[0]:
            return True
    else:
        return False


def select_final_time(conn, day, id):
    """
    Return ending time of final lesson student must attend, or None.
    :param conn: Connection object
    :param day: current weekday, lowercase str
    :param id: ID of student, int
    """
    cur = conn.cursor()
    cur.execute("""
        SELECT end_time
        FROM timetable
            INNER JOIN students ON g1 = lesson_id
                OR g2 = lesson_id
                OR g3 = lesson_id
                OR g4 = lesson_id
                OR g5 = lesson_id
                OR g6 = lesson_id
                OR lesson_id = 'gu'
                OR leeson_id = 'to'
        WHERE id = ? AND day = ?
        ORDER BY end_time DESC
        LIMIT 1
        """, (id, day))
    finish = cur.fetchone()
    if str(type(finish)) == "<class 'tuple'>":
        return finish[0]
    else:
        return finish


def parse_time_string(timestring):
    """
    Parse given 24h time string of format "HH:MM" into time_struct
    :param timestring: time string "HH:MM"
    """
    timestruct = time.strptime(timestring, "%H:%M")
    return timestruct


def main():
    db = input(
        "Please enter name of database (located in the same folder as the program): ")

    y = "y"
    while y == "y":
        conn = connect_database(db)
        day = get_lower_weekday()
        id = int(input("Please input the student ID number: "))

        if check_id(conn, id):
            raw = select_final_time(conn, day, id)
            final = parse_time_string(raw) if raw != None else None

            if final != None:
                current_time = parse_time_string(time.strftime("%H:%M"))

                if current_time > final:
                    print("Clear to leave.")
                else:
                    print("Student does not have clearance.")
            elif final == None:
                print("Clear to leave.")

        y = input("Press y and enter to run again.")


if __name__ == "__main__":
    main()
