# 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 configuration
import utils
from telegram import ChatAction

def is_authorized(message, operation):
    conn = sqlite3.connect(configuration.db_users_path)
    c = conn.cursor()

    selectData = (str(message.chat.id))

    if (operation == 'webcam_allowed'):
        c.execute("SELECT COUNT(*) FROM USERS WHERE chat_id = ? and webcam_allowed = 1", [selectData])
    elif (operation == 'chat_allowed'):
        c.execute("SELECT COUNT(*) FROM USERS WHERE chat_id = ? and chat_allowed = 1", [selectData])
    elif (operation == 'admin'):
        c.execute("SELECT COUNT(*) FROM USERS WHERE chat_id = ? and admin = 1", [selectData])
    result = int(c.fetchone()[0])

    conn.close()

    if (result > 0):
        return True
    return False


def add_me(bot, update):
    bot.sendChatAction(chat_id=update.message.chat.id, action=ChatAction.TYPING)
    if (utils.is_private(update.message)):
        conn = sqlite3.connect(configuration.db_users_path)
        c = conn.cursor()

        selectData = (str(update.message.chat.id))
        c.execute("SELECT COUNT(*) FROM USERS WHERE chat_id = ?", [selectData])
        result = int(c.fetchone()[0])
        print(result)
        if (result == 0):
            insertData = (
                str(update.message.chat.id), str(update.message.chat.first_name), str(update.message.chat.last_name),
                str(utils.get_timestamp()),
                str(utils.get_timestamp()), 0, 0, 0)
            c.execute("INSERT INTO USERS VALUES (null,?,?,?,?,?,?,?,?)", insertData)
            conn.commit()
            bot.sendMessage(chat_id=update.message.chat.id, text='Your request has been submitted.');
        else:
            bot.sendMessage(chat_id=update.message.chat.id, text='Request already submitted.');
        conn.close()


def user(bot, update):
    if is_authorized(update.message, 'admin'):
       bot.sendMessage(chat_id=update.message.chat.id,text='Not implemented yet.')