# L-29 MCS 275 Fri 17 Mar 2017 : scripts_server.py
"""
Database server to scripts in OurPyFiles database.
Sends number of scripts in the table 'scripts'
in the MySQL database 'OurPyFiles' to the client.
"""
# import MySQLdb
import pymysql
from socket import socket as Socket

HOSTNAME = ''      # use any address
PORTNUMBER = 11267 # number for the port
BUFFER = 80        # size of the buffer

def connect():
    """
    Returns client and server socket
    to communicate with one client.
    """
    from socket import AF_INET, SOCK_STREAM
    server_address = (HOSTNAME, PORTNUMBER)
    server = Socket(AF_INET, SOCK_STREAM)
    server.bind(server_address)
    server.listen(1)
    print('server waits for connection')
    client, client_address = server.accept()
    print('server accepted connection from ',\
        client_address)
    return client, server

def count():
    """
    Returns the number of scripts.
    """
    # ourdb = MySQLdb.connect(db='OurPyFiles')
    ourdb = pymysql.connect(db='OurPyFiles')
    crs = ourdb.cursor()
    qry = 'select count(*) from scripts'
    crs.execute(qry)
    res = crs.fetchone()
    nbr = int(res[0])
    return nbr

def main():
    """
    Accepts connection and sends result.
    """
    client, server = connect()
    print('server connects to database')
    nbr = count()
    print('server sends #scripts to client')
    data = str(nbr)
    client.send(data.encode())
    print('count sent, closing off')
    server.close()

main()
