from gi.repository import Gtk, Gdk, GdkPixbuf
from kutuphaneler import diller
import subprocess, os

class StDisk(Gtk.Grid):
	def __init__(self,ebeveyn):
		Gtk.Window.__init__(self)
		self.ebeveyn = ebeveyn
		self.baslik = "Disk Ayarları"
		self.ad = "Disk"
		self.set_column_spacing(5)
		self.set_row_spacing(5)
		self.diskler_liste = {}
		self.oto_ata = True
		self.disk = None
		
		self.bilgi_label = Gtk.Label()
		self.bilgi_label.set_max_width_chars(70)
		self.bilgi_label.set_line_wrap(True)
		self.bilgi_label.set_use_markup(True)
		self.attach(self.bilgi_label,0,0,4,1)

		self.diskler_yazi = Gtk.Label()
		self.attach(self.diskler_yazi,0,1,2,1)

		self.disk_yenile = Gtk.Button()
		self.disk_yenile.connect("clicked", self.disk_doldur)
		self.disk_yenile.set_always_show_image(True)
		self.disk_yenile.set_image(Gtk.Image(stock=Gtk.STOCK_REFRESH))
		self.attach(self.disk_yenile,2,1,1,1)
		self.set_baseline_row(2)

		self.disk_duzenle = Gtk.Button()
		self.disk_duzenle.connect("clicked", self.disk_duzenle_surec)
		self.disk_duzenle.set_always_show_image(True)
		self.disk_duzenle.set_image(Gtk.Image(stock=Gtk.STOCK_EDIT))
		self.attach(self.disk_duzenle,3,1,1,1)

		self.disk_liste_store = Gtk.ListStore(GdkPixbuf.Pixbuf(),str,str,str,str,str)
		self.disk_liste = Gtk.TreeView(model = self.disk_liste_store)
		self.disk_liste.connect("row-activated",self.disk_liste_tiklandi)
		self.disk_liste.set_activate_on_single_click(True)

		sutun_icon = Gtk.CellRendererPixbuf()
		sutun_icon.set_fixed_size(32,32)
		self.sutun_icon = Gtk.TreeViewColumn("Simge",sutun_icon, gicon = 0)
		self.disk_liste.append_column(self.sutun_icon)

		sutun_text = Gtk.CellRendererText()
		self.sutun_ad = Gtk.TreeViewColumn("Ad",sutun_text, text = 1)
		self.disk_liste.append_column(self.sutun_ad)

		sutun_text = Gtk.CellRendererText()
		self.sutun_format = Gtk.TreeViewColumn("Format",sutun_text, text = 2)
		self.disk_liste.append_column(self.sutun_format)

		sutun_text = Gtk.CellRendererText()
		self.sutun_boyut = Gtk.TreeViewColumn("Boyut",sutun_text, text = 3)
		self.disk_liste.append_column(self.sutun_boyut)

		sutun_text = Gtk.CellRendererText()
		self.sutun_kullanim = Gtk.TreeViewColumn("Kullanım",sutun_text, text = 4)
		self.disk_liste.append_column(self.sutun_kullanim)

		sutun_text = Gtk.CellRendererText()
		self.sutun_bayrak = Gtk.TreeViewColumn("Bayraklar",sutun_text, text = 5)
		self.disk_liste.append_column(self.sutun_bayrak)

		scroll = Gtk.ScrolledWindow()
		scroll.set_min_content_width(630)
		scroll.set_min_content_height(190)
		scroll.set_policy(Gtk.PolicyType.AUTOMATIC,Gtk.PolicyType.AUTOMATIC)
		scroll.add(self.disk_liste)

		self.attach(scroll,0,2,4,1)

		self.disk_doldur(None)

	def disk_liste_tiklandi(self,widget,path,coloumn):
		satir = self.disk_liste_store[path]
		menu = Gtk.Menu()
		##############################################################
		#if satir[2].startswith('linux-swap'):
		menu_takas = Gtk.ImageMenuItem(diller.diller[self.dil]["t34"])
		menu_takas.connect("activate",self.takas_diski_ata, satir)
		icon = Gtk.Image.new_from_file("{}/takas-32.svg".format(self.ebeveyn.resim_yol))
		menu_takas.set_image(icon)
		menu.add(menu_takas)
		###############################################################
		#elif satir[2] == "ext4":
		menu_sistem = Gtk.ImageMenuItem(diller.diller[self.dil]["t33"])
		menu_sistem.connect("activate",self.sistem_diski_ata, satir)
		icon = Gtk.Image.new_from_file("{}/milis-logo-32.svg".format(self.ebeveyn.resim_yol))
		menu_sistem.set_image(icon)
		menu.add(menu_sistem)
		###############################################################
		#elif satir[2] == "fat32":
		menu_efi = Gtk.ImageMenuItem(diller.diller[self.dil]["t35"])
		menu_efi.connect("activate",self.efi_diski_ata, satir)
		icon = Gtk.Image.new_from_file("{}/uefi-32.svg".format(self.ebeveyn.resim_yol))
		menu_efi.set_image(icon)
		menu.add(menu_efi)
		###############################################################
		menu.attach_to_widget(widget)
		menu.show_all()
		menu.popup_at_pointer()

	def takas_diski_ata(self,widget,disk):
		disk = "{} swap {} [SWAP] 1".format(disk[1],disk[3])
		print(disk)
		self.disk_temizle(disk)
		self.ebeveyn.milis_ayarlari["takas_disk"] = disk
		self.disk_secildi()

	def sistem_diski_ata(self,widget,disk):
		disk = "{} ext4 {} / 1".format(disk[1],disk[3])
		print(disk)
		self.disk_temizle(disk)
		self.ebeveyn.milis_ayarlari["sistem_disk"] = disk
		if not os.path.exists("/sys/firmware/efi") or (os.path.exists("/sys/firmware/efi") and self.ebeveyn.milis_ayarlari["uefi_disk"] != ""):
			self.ebeveyn.ileri_dugme.set_sensitive(True)
		self.disk_secildi()

	def efi_diski_ata(self,widget,disk):
		disk = "{} vfat {} /boot/efi 1".format(disk[1],disk[3])
		print(disk)
		self.disk_temizle(disk)
		self.ebeveyn.milis_ayarlari["uefi_disk"] = disk
		if os.path.exists("/sys/firmware/efi") and self.ebeveyn.milis_ayarlari["sistem_disk"] != "":
			self.ebeveyn.ileri_dugme.set_sensitive(True)
		self.disk_secildi()

	def disk_temizle(self,disk):
		for i in ["sistem_disk","uefi_disk","takas_disk"]:
			if self.ebeveyn.milis_ayarlari[i].split(" ")[0] == disk.split(" ")[0]:
				self.ebeveyn.milis_ayarlari[i] = ""

	def disk_duzenle_surec(self,widget):
		surec = subprocess.Popen(['gparted',self.disk.split(" ")[0]])
		surec.wait()
		self.disk_doldur(None)

	def disk_doldur(self,widget):
		#Tekrar disk doldurunca oto atama tekrar yapılacak
		self.ebeveyn.milis_ayarlari["takas_disk"] = ""
		self.ebeveyn.milis_ayarlari["sistem_disk"] = ""
		self.ebeveyn.milis_ayarlari["uefi_disk"] = ""
		if self.ebeveyn.stack_secili == 5:
			self.ebeveyn.ileri_dugme.set_sensitive(False)

		self.diskler = {}
		process = subprocess.check_output(["lsblk","-P","-no","PATH,SIZE,FSTYPE,TYPE,PARTFLAGS,MODEL"], timeout=2)
		out = process.decode("UTF-8").rstrip()
		out = out.split("\n")
		for i in out:
			k = i.split()
			path = k[0].replace("PATH=","").replace('"','')
			size = k[1].replace("SIZE=","").replace('"','')
			fstype = k[2].replace("FSTYPE=","").replace('"','')
			type_ = k[3].replace("TYPE=","").replace('"','')
			flags = k[4].replace("PARTFLAGS=","").replace('"','')
			model = k[5].replace("MODEL=","").replace('"','')
			if type_ == "disk" and "/dev/fd" not in path: 
				self.diskler[path] = {"SIZE":size, "MODEL":model, "PARTITIONS":[]}
			elif type_ == "part":
				for key in self.diskler.keys():
					if key in path:
						self.diskler[key]["PARTITIONS"].append([path,size,fstype,type_,flags])
		self.disk_secildi()

	def disk_secildi(self):
		disk = self.disk
		if disk != None:
			disk = disk.split(" | ")[0]
			self.diskler_yazi.set_text(diller.diller[self.dil]["t31"].format(disk))
			self.disk_liste_store.clear()
			sayac = 0

			s_diskler = self.secili_diskler_ayikla()
			d = list(self.diskler[disk]["PARTITIONS"])
			d.sort()
			for bolum in d:
				if sayac > 9:
					icon_name = str(sayac)[-1]
				else:
					icon_name = str(sayac)
				icon_name = self.ebeveyn.resim_yol + "/" + icon_name + ".svg"
				icon = GdkPixbuf.Pixbuf.new_from_file(icon_name)
				if s_diskler[0] and s_diskler[0] == bolum[0]:
					bagnok = "/"
				elif s_diskler[1] and s_diskler[1] == bolum[0]:
					bagnok = "[SWAP]"
				elif s_diskler[2] and s_diskler[2] == bolum[0]:
					bagnok = "/boot/efi"
				else:
					bagnok = ""
				#Efi diski ön tanımlı olarak atanacak
				if "boot" in bolum[4] and "esp" in bolum[4] and self.oto_ata:
					bagnok = "/boot/efi"
					tur = bolum[2]
					if tur == "fat32":
						tur = "vfat"
					disk = "{} {} {} /boot/efi 0".format(bolum[0],tur,bolum[1])
					self.ebeveyn.milis_ayarlari["uefi_disk"] = disk
					self.oto_ata = False
				self.disk_liste_store.append([icon,bolum[0],bolum[2],bolum[1],bagnok,bolum[4]])
				sayac += 1

	def secili_diskler_ayikla(self):
		sistem_disk = self.ebeveyn.milis_ayarlari["sistem_disk"]
		takas_disk = self.ebeveyn.milis_ayarlari["takas_disk"]
		efi_disk = self.ebeveyn.milis_ayarlari["uefi_disk"]
		if sistem_disk == "":
			sistem_disk = False
		else:
			sistem_disk = sistem_disk.split()[0]
		if takas_disk == "":
			takas_disk = False
		else:
			takas_disk = takas_disk.split()[0]
		if efi_disk == "":
			efi_disk = False
		else:
			efi_disk = efi_disk.split()[0]
		return (sistem_disk, takas_disk, efi_disk)


	def dil_ata(self,dil):
		self.dil = dil
		self.baslik = diller.diller[dil]["t29"]
		self.bilgi_label.set_markup(diller.diller[dil]["t30"])
		self.disk_yenile.set_label(diller.diller[dil]["t32"])
		self.disk_duzenle.set_label(diller.diller[dil]["t36"])
		self.sutun_icon.set_title(diller.diller[dil]["t67"])
		self.sutun_ad.set_title(diller.diller[dil]["t68"])
		self.sutun_format.set_title(diller.diller[dil]["t69"])
		self.sutun_boyut.set_title(diller.diller[dil]["t70"])
		self.sutun_kullanim.set_title(diller.diller[dil]["t71"])
		self.sutun_bayrak.set_title(diller.diller[dil]["t72"])
