import sqlalchemy as db
import json

def download():
    db_URI = 'mysql+pymysql://mdownload:mdownload@192.168.86.198:3306/Downloads'

    engine = db.create_engine(db_URI)
    con = engine.connect()

    metadata = db.MetaData()

    url_metadata = db.Table('url_metadata', metadata, autoload = True, autoload_with= engine)
    manga = db.Table('manga', metadata, autoload=True, autoload_with=engine)
    # query = db.select([manga.columns.url, url_metadata.columns.base_url, manga.columns.url_flag])
    query = db.text(""" select manga.url, url_metadata.base_url , manga.name from manga join url_metadata on manga.url_flag = url_metadata.flag """)
    result = con.execute(query).fetchall()
    y=0
    url = []
    base = []
    name = []
    PATH = 'Manga/'
    # PATH = 'smb://MediaServer._smb._tcp.local/Downloads/Manga/'
    for x in result:
        # print(result[y][0])
        url.append(result[y][0])
        base.append(result[y][1])
        name.append(result[y][2])

        # print(base[y]+url[y])
        query = """ select active from manga where manga_id = """ + str(y+1)
        active = con.execute(query).fetchone()

        if active[0] != 0:
            print("""manga-py """ + base[y]+url[y] + """ -n \"""" + name[y] + """\" -d \"""" + PATH + """\" -z -g """)
        y = y+1

def upload_jason():
    url = []
    base = []
    name = []
    y = 0
    z = 0

    db_URI = 'mysql+pymysql://mdownload:mdownload@192.168.86.198:3306/Downloads'

    engine = db.create_engine(db_URI)
    con = engine.connect()
    metadata = db.MetaData()
    manga = db.Table('manga', metadata, autoload=True, autoload_with=engine)

    with open("tach.json", "r") as tf:
        data = json.load(tf)
        for x in data["mangas"]:
            # Manga Name
            name.append(data["mangas"][y]["manga"][1])
            # Mange URL
            url.append(data["mangas"][y]["manga"][0])
            # Mange Base URL
            base.append(data["mangas"][y]["manga"][2])
            y=y+1
        # query = """ Delete from manga"""
        # con.execute(query)
        # query = """ Alter table manga auto_increment = 1 """
        # con.execute(query)
        for x in name:
            query = """select name from manga where name = \"""" + name[z] + """\""""
            exists = con.execute(query).fetchone()
            if exists == None  or exists[0] != name[z]:
                query = """ insert into manga(name, url, url_flag, view_format, unknown_value) values (\"""" + name[z] + """\",\"""" + url[z] + """\",\"""" + str(base[z]) + """\",\"0\",\"0\")"""
                print(query)
                con.execute(query)
            else:
                continue
            z=z+1

while True:
    print("1. Download \n 2. Upload")
    val = input(">>>")
    if val == "1":
        download()
    elif val == "2":
        upload_jason()