from ftplib import FTP
from tkinter import messagebox
import pymysql as mysql
import sqlite3 as sqlite
import os


def flag_write(mode, flag):
    if flag == "ftp":
        return open("settings.conf", mode)
    elif flag == "pdf":
        return open("pdf.conf", mode)


class SQLConfig:

    def __init__(self, placeholder = False):
        if placeholder == False:
            fileSource = open("mysql.conf", "r+")
            fetchedInfo = fileSource.read().split("\n")
            self.host = fetchedInfo[0]
            self.username = fetchedInfo[1]
            self.password = fetchedInfo[2]
            self.database = fetchedInfo[3]
            self.table = fetchedInfo[4]
            fileSource.close()
        else:
            self.host = "Host"
            self.username = "Kullanıcı Adı"
            self.password = "Şifre"
            self.database = "Veri Bankası"
            self.table = "Tablo"


class Configuration:

    def __init__(self, flag="ftp", placeholder = False):
        if placeholder == False:
            fileSource = flag_write("r+", flag=flag)
            fetchedInfo = fileSource.read().split("\n")
            self.domain = fetchedInfo[0]
            self.username = fetchedInfo[1]
            self.password = fetchedInfo[2]
            fileSource.close()
        else:
            self.domain = "Domain"
            self.username = "Kullanıcı Adı"
            self.password = "Şifre"


def saveSQL(host, username, password, database, table):
    fileTarget = open("mysql.conf", "w")
    fileTarget.write(host + "\n" + username + "\n" + password + "\n" + database
                     + "\n" + table)
    fileTarget.close()
    messagebox.showinfo("Başarılı", "Ayarlar başarı ile kaydedildi.")


def save(domain, domainSent, password, flag="ftp"):
    fileTarget = flag_write("w+", flag=flag)
    fileTarget.write(domain + "\n" + domainSent + "\n" + password)
    fileTarget.close()
    messagebox.showinfo("Başarılı", "Ayarlar başarı ile kaydedildi.")


def equlize():
    conf = SQLConfig()
    initSQL = mysql.connect(conf.host, conf.username, conf.password,
                            conf.database, charset="utf8")
    initCursor = initSQL.cursor()
    initCursor.execute("SELECT * FROM {}".format(conf.field1, conf.field2,
                       conf.table))
    fetchedData = initCursor.fetchall()
    initSQL.close()
    os.remove("kütüphane.db")
    targetSQL = sqlite.connect("kütüphane.db")
    targetCursor = targetSQL.cursor()
    targetCursor.execute("CREATE TABLE kitaplar(Isim TEXT, Sahip TEXT)")
    targetSQL.commit()
    for i in range(len(fetchedData)):
        j = fetchedData[i]
        owner = j[3]
        if j[3] != "Kütüphane":
            owner = "Kütüphane"
        targetCursor.execute("INSERT INTO kitaplar values(\"{}\","
                             " \"{}\")".format(j[0], owner))
    targetSQL.commit()
    targetSQL.close()


def sync():
    conf = Configuration()
    fileSource = open("kütüphane.db", "rb")
    beacon = FTP(conf.domain)
    beacon.login(conf.username, conf.password)
    beacon.storbinary("STOR library.db", fileSource)
    beacon.quit()
    fileSource.close()
    messagebox.showinfo("Başarılı", "Aktarım başarı ile tamamlandı.")


def uploadEbook(pdffile):
    conf = Configuration(flag="pdf")
    fileSource = open(pdffile, "rb")
    beacon = FTP(conf.domain)
    beacon.login(conf.username, conf.password)
    beacon.storbinary("STOR {}".format(pdffile), fileSource)
    beacon.quit()
    fileSource.close()
    messagebox.showinfo("Başarılı", "Aktarım başarı ile tamamlandı.")
