from enum import Enum
from ftplib import FTP
import os
import subprocess


class ITezgahlar: pass


class TezgahKlasorDurumları(Enum):
    klasorYok = 0
    aktifYontemYok = 1
    tezgahProgramiYok = 2


class FtpUploadTracker:
    sizeWritten = 0
    lastShownPercent = 0

    def __init__(self, itm, YuzdeF, Dsy):
        self.totalSize = int(os.path.getsize(Dsy))
        self.itm = itm
        self.YuzdeFunc = YuzdeF

    def handle(self, block):
        self.sizeWritten += 1024
        percentComplete = ((self.sizeWritten / self.totalSize) * 100)

        if (self.lastShownPercent != percentComplete):
            self.lastShownPercent = percentComplete
            if self.YuzdeFunc != None:
                self.YuzdeFunc(self.itm, "", percentComplete)


class ITezgah():
    def __init__(self, data:dict={}):
        super(ITezgah, self).__init__()
        # --->
        self.__orjData = data
        for key in data:
            setattr(self, key, data[key])

    def guncellenmis(self) -> bool:
        match = False
        for key in self.__orjData:
            if not key in self.__dict__ or self.__orjData[key] != self.__dict__[key]:
                match = True
        return match

    def dosyaGonder(self, Dosya:str, YuzdeFunc=None) -> bool:
        if self.tezgahKlasoruAktif:
            source_size = os.stat(Dosya).st_size
            copied = 0
            source = open(Dosya, 'rb')
            target = open(os.path.join(self.tezgahKlasoru, os.path.basename(Dosya)), 'wb')

            while True:
                chunk = source.read(32768)
                if not chunk:
                    break
                target.write(chunk)
                copied += len(chunk)
                if YuzdeFunc != None:
                    YuzdeFunc(self, Dosya, (copied * 100 / source_size))

            source.close()
            target.close()

        if self.tezgahProgramiAktif:
            if os.path.isfile(self.ncGondermeProgrami):
                self.anaProgram.fikoSistem.dosyaSistemi.programCalistirBekle(
                    self.ncGondermeProgrami + ' "' + Dosya + '"')

        if self.tezgahFtpAktif:
            # --->
            ftp = FTP(self.ftpSunucuAdresi)
            ftp.login(self.ftpKullaniciAdi, self.ftpSifresi)
            f = open(Dosya, 'rb')
            # --->
            uploadTracker = FtpUploadTracker(self, YuzdeFunc, Dosya)
            ftp.storbinary('STOR ' + os.path.basename(Dosya), f, blocksize=1024, callback=uploadTracker.handle)

    def tezgahAc(self):
        if not self.tezgahKlasoruAktif and not self.tezgahProgramiAktif and not self.tezgahFtpAktif:
            return TezgahKlasorDurumları.aktifYontemYok

        if self.tezgahKlasoruAktif:
            if os.path.isdir(str(self.tezgahKlasoru)):
                os.startfile(self.tezgahKlasoru)
            else:
                return TezgahKlasorDurumları.klasorYok
                # --->
        if self.tezgahProgramiAktif:
            print(self.tezgahProgrami)
            if os.path.exists(str(self.tezgahProgrami)):
                args = str(self.tezgahProgrami)
                os.startfile(args)
            else:
                return TezgahKlasorDurumları.tezgahProgramiYok
        # --->
        if self.tezgahFtpAktif:
            args = ['C:\Windows\explorer.exe',
                    'ftp://' + self.ftpKullaniciAdi + ':' + self.ftpSifresi + '@' + self.ftpSunucuAdresi]
            subprocess.call(args)


    def tezgahiTemizle(self):
        if self.tezgahKlasoruAktif:
            Dosyalar = self.anaProgram.fikoSistem.klasordekiDosyalar(self.tezgahKlasoru, "*." + self.postUzantisi)
            for x in range(len(Dosyalar)):
                os.remove(Dosyalar[x])

        if self.tezgahProgramiAktif:
            if os.path.isfile(self.tezgahProgrami):
                self.anaProgram.fikoSistem.dosyaSistemi.programCalistirBekle(self.tezgahProgrami)

        if self.tezgahFtpAktif:
            ftp = FTP(self.ftpSunucuAdresi)
            ftp.login(self.ftpKullaniciAdi, self.ftpSifresi)
            dosyalar = ftp.nlst()
            for x in range(len(dosyalar)):
                if dosyalar[x] != "." and dosyalar[x] != "..":
                    ftp.delete(dosyalar[x])

    def __str__(self) -> str:
        return repr(self.ismi)


import  Projeler.QTBilesenleri.FikoBehemilPost.ITezgahlar
