import datetime
import os
import sqlite3
import subprocess

from IFikomObject import IFikoObject


class ITezgahlar: pass


class ITezgah: pass


class IProcessDokuman:pass


def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d


class IFikoPost(IFikoObject):
    def __init__(self, sahip:IProcessDokuman=None):
        super(IFikoPost, self).__init__(sahip=sahip)
        self.sahip = sahip
        self.anaProgram = sahip.anaProgram
        # --->
        self.__processDokuman = sahip
        self.__tezgahlar = ITezgahlar(sahip=self)
        self.__tezgah = ITezgah(sahip=self.__tezgahlar)
        #--->
        self.aptler = []

    @property
    def tezgahlar(self) -> ITezgahlar:
        return self.__tezgahlar

    @tezgahlar.setter
    def tezgahlar(self, value:ITezgahlar):
        self.__tezgahlar = value

    @property
    def tezgah(self) -> ITezgah:
        Klasor = os.path.join(self.__processDokuman.klasoru, "Fikomantasyon")
        # --->
        if not os.path.exists(Klasor):
            os.makedirs(Klasor)

        if not os.path.isfile(os.path.join(Klasor, 'Fikomantasyon.fikodb')):
            conn = sqlite3.connect(os.path.join(Klasor, 'Fikomantasyon.fikodb'))
            conn.execute("""
                CREATE TABLE hareketler
                (
                    _id INTEGER PRIMARY KEY AUTOINCREMENT,
                    modul TEXT,
                    olay TEXT,
                    veri TEXT,
                    saat DATETIME
                );
              """)

            conn.execute("""
            INSERT INTO hareketler (modul, olay, veri, saat) VALUES ('IFikoPost', 'tezgahSecildi', :tezgah, :saat);
            """, {"tezgah": self.tezgahlar.tezgahlarTumu[0].ismi, "saat": datetime.datetime.now()})
            conn.commit()
            # self.__tezgah = self.tezgahlar.tezgahlarTumu[0]

        conn = sqlite3.connect(os.path.join(Klasor, 'Fikomantasyon.fikodb'))
        conn.row_factory = dict_factory
        __C = conn.cursor()
        __C.execute(
            """SELECT * FROM hareketler WHERE modul = 'IFikoPost' AND olay='tezgahSecildi' ORDER BY _id DESC """)
        veriler = __C.fetchone()
        if veriler is None:
            __C.execute("""
            INSERT INTO hareketler (modul, olay, veri, saat) VALUES ('IFikoPost', 'tezgahSecildi', :tezgah, :saat);
            """, {"tezgah": self.tezgahlar.tezgahlarTumu[0].ismi, "saat": datetime.datetime.now()})
            conn.commit()
            self.__tezgah =  self.tezgahlar.tezgahlarTumu[0]
            return self.__tezgah
        self.__tezgah = self.tezgahlar.item(veriler["veri"])

        return self.__tezgah

    @tezgah.setter
    def tezgah(self, value:ITezgah):
        Klasor = os.path.join(self.__processDokuman.klasoru, "Fikomantasyon")
        # --->
        if not os.path.exists(Klasor):
            os.makedirs(Klasor)

        if not os.path.isfile(os.path.join(Klasor, 'Fikomantasyon.fikodb')):
            conn = sqlite3.connect(os.path.join(Klasor, 'Fikomantasyon.fikodb'))
            conn.execute("""
                CREATE TABLE hareketler
                (
                    _id INTEGER PRIMARY KEY AUTOINCREMENT,
                    modul TEXT,
                    olay TEXT,
                    veri TEXT,
                    saat DATETIME
                );
              """)
            conn.commit()
            conn.close()
        conn = sqlite3.connect(os.path.join(Klasor, 'Fikomantasyon.fikodb'))
        conn.execute("""
            INSERT INTO hareketler (modul, olay, veri, saat) VALUES ('IFikoPost', 'tezgahSecildi', :tezgah, :saat);
            """, {"tezgah": value, "saat": datetime.datetime.now()})
        conn.commit()

        self.__tezgah = self.__tezgahlar.item(value)


    @property
    def processDokuman(self) -> IProcessDokuman:
        return self.__processDokuman


    @processDokuman.setter
    def processDokuman(self, value:IProcessDokuman):
        self.__processDokuman = value


    @property
    def partOperasyonlari(self):
        return self.__processDokuman.partOperasyonlari


    @partOperasyonlari.setter
    def partOperasyonlari(self, value):
        self.__processDokuman.partOperasyonlari = value

    def postlariKlasoreTasi(self, val=None):
        return self.processDokuman.postlariKlasoreTasi(val)

    def klasoruTemizle(self, val=None):
        self.processDokuman.klasoruTemizle(val)

    def aptleriUret(self, val:list=None):
        for prg in val:
            self.aptler.append(prg.apt)
        self.uretilenApteleriNcKodaCevir()

    def uretilenApteleriNcKodaCevir(self):
        anaProgram = self.anaProgram
        __tezgah = self.tezgah
        ayarlar = anaProgram.fikoSistem.ayarlar
        proclist = []
        for apt in self.aptler:
            KuralDosyasi = "\"" + os.path.join( anaProgram.scriptYolu ,ayarlar.item("ncKuralDosyasıKlasörü").asStr, __tezgah.kuralDosyasi ) + "\""
            AptDosyasi = "\"" + apt + "\""
            if ayarlar.item("ncÇıktıKlasörü").asInt == 0:
                NcDosyasi = "\"" + os.path.join( os.path.join(os.path.dirname(apt),os.path.basename(apt).replace("."+ayarlar.item("aptUzantısı").degeri,"")) + "." + __tezgah.postUzantisi) + "\""
            elif isinstance(ayarlar.item("ncÇıktıKlasörü").degeri, str):
                NcDosyasi = "\"" + os.path.join(ayarlar.item("ncÇıktıKlasörü").degeri , self.ismi + "." + __tezgah.postUzantisi) + "\""


            CeviriciParam = ayarlar.item("ncÇeviriciParametreler").degeri
            Parametreler = KuralDosyasi + " " + AptDosyasi + " " + NcDosyasi + " " + CeviriciParam

            Popen_arg = os.path.join(anaProgram.scriptYolu, ayarlar.item("ncÇeviriciProgram").asStr ) + " " + Parametreler
            proclist.append(anaProgram.fikoSistem.dosyaSistemi.programCalistir(Popen_arg))

            # if __tezgah.postDuzenlemeProgrami != None:
            #     Popen_arg = "\""+os.path.join(anaProgram.scriptYolu, __tezgah.postDuzenlemeProgrami )+"\"" + " " + NcDosyasi
            #     print(Popen_arg)
            #     subprocess.Popen(Popen_arg,shell=True)
        # --->
        for x in  range(len(proclist)):
            while proclist[x].is_running():
                pass
            else:
                if x ==len(proclist)-1:
                    self.klasoruTemizle(val=["log", "FikoApt_LOG", "LOG"])
        if __tezgah.postDuzenlemeProgrami != None:
            Popen_arg = "python \""+os.path.join(anaProgram.scriptYolu, __tezgah.postDuzenlemeProgrami )+"\"" + " " + NcDosyasi
            print(Popen_arg)
            anaProgram.fikoSistem.dosyaSistemi.programCalistirBekle(Popen_arg)
            # subprocess.Popen(Popen_arg)



from .ITezgahlar import ITezgahlar
from .ITezgah import ITezgah
from IProcessDokuman import IProcessDokuman