import json
import requests
import pyrebase
import firebase_admin
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.properties import StringProperty
from requests.exceptions import HTTPError
from kivymd.uix.navigationbar import MDNavigationBar, MDNavigationItem
from kivymd.uix.screenmanager import MDScreenManager
from kivymd.uix.screen import MDScreen
from kivymd.uix.snackbar import MDSnackbar,MDSnackbarText,MDSnackbarCloseButton, MDSnackbarButtonContainer

class FirstWindow(MDScreen):
	pass
class SecondWindow(MDScreen):
	pass
class ThirdWindow(MDScreen):
	pass
class FourthWindow(MDScreen):
	pass
class HomeWindow(MDScreen):
	pass
class SettingsWindow(MDScreen):
	pass
class WindowManager(MDScreenManager):
	pass

Window.size = (350,600)
Window.clearcolor = (57/255,64/255,83/255,1)

class BaseMDNavigationItem(MDNavigationItem):
    icon = StringProperty()
    text = StringProperty()

class MainApp(MDApp):

	def on_switch_tabs(
		self,
		bar: MDNavigationBar,
		item: MDNavigationItem,
		item_icon: str,
		item_text: str,):
		self.root.get_screen("fourth").ids.screen_manager.current = item_text
	
	def kayit_ol_button(self):
		self.root.current = "second"
		self.root.transition.direction = "left"

	def giris_yap_button(self):
		self.root.current = "fourth"
		self.root.transition.direction = "left"

	def kayit_ol(self):
		email = self.root.get_screen("second").ids.kayit_ol_email.text
		username = self.root.get_screen("second").ids.kayit_ol_username.text
		password = self.root.get_screen("second").ids.kayit_ol_password.text
		
		try:
			self.auth.create_user_with_email_and_password(email=email,password=password)
		except Exception as e:
			e = "{\n" + str(e).replace("] {","_______").split("_______")[1].strip()
			json_data = json.loads(e)
			hata_mesaji = json_data["error"]["message"]
			MDSnackbar(
				MDSnackbarText(
					text=hata_mesaji,
				),
				MDSnackbarButtonContainer(
					MDSnackbarCloseButton(
						icon="close",
					),
					pos_hint={"center_y": 0.5}
				),
				y=24,
				orientation="horizontal",
				pos_hint={"center_x": 0.5},
			).open()
		
		try:
			self.auth.sign_in_with_email_and_password(email=email,password=password)
		except Exception as e:
			e = "{\n" + str(e).replace("] {","_______").split("_______")[1].strip()
			json_data = json.loads(e)
			hata_mesaji = json_data["error"]["message"]
			MDSnackbar(
				MDSnackbarText(
					text=hata_mesaji,
				),
				MDSnackbarButtonContainer(
					MDSnackbarCloseButton(
						icon="close",
					),
					pos_hint={"center_y": 0.5}
				),
				y=24,
				orientation="horizontal",
				pos_hint={"center_x": 0.5},
			).open()

		if self.auth.current_user != None:
			self.root.current = "fourth"
			self.root.transition.direction = "left"
			refresh_token = self.auth.current_user["refreshToken"]
			self.global_username = self.auth.current_user["displayName"]
			self.global_email = self.auth.current_user["email"]
			self.auth.update_profile(id_token=self.auth.current_user["idToken"],display_name=username)

			with open("refresh_token.txt","w",encoding="utf-8") as file:
				file.write(refresh_token)
	
	def giris_yap(self):
		email = self.root.get_screen("third").ids.giris_yap_email.text
		password = self.root.get_screen("third").ids.giris_yap_parola.text
		try:
			self.auth.sign_in_with_email_and_password(email=email,password=password)
		except Exception as e:
			e = "{\n" + str(e).replace("] {","_______").split("_______")[1].strip()
			json_data = json.loads(e)
			hata_mesaji = json_data["error"]["message"]
			MDSnackbar(
				MDSnackbarText(
					text=hata_mesaji,
				),
				MDSnackbarButtonContainer(
					MDSnackbarCloseButton(
						icon="close",
					),
					pos_hint={"center_y": 0.5}
				),
				y=24,
				orientation="horizontal",
				pos_hint={"center_x": 0.5},
			).open()

		if self.auth.current_user != None:
			self.root.current = "fourth"
			self.root.transition.direction = "left"
			refresh_token = self.auth.current_user["refreshToken"]
			self.global_username = self.auth.current_user["displayName"]
			self.global_email = self.auth.current_user["email"]

			with open("refresh_token.txt","w",encoding="utf-8") as file:
				file.write(refresh_token)

	def giris_on(self):
		self.root.current = "fourth"
		self.root.transition.direction = "left"

	def build(self):
		self.title = "Nowi"
		self.icon = "images/icon.png"

		#-#-#-# PYREBASE #-#-#-#
		config = {
		"apiKey": "",
		"authDomain": "",
		"databaseURL": "",
		"storageBucket": ""
		}

		self.pyrebase_firebase = pyrebase.initialize_app(config)
		self.auth = self.pyrebase_firebase.auth()
		#-#-#-#-#-#-#-#-#-#-#-#

		with open("refresh_token.txt","r",encoding="utf-8") as file:
			refresh_token = file.read()
			if len(refresh_token) > 0:
				self.global_userid = self.auth.refresh(refresh_token=refresh_token)["userId"]
				self.global_idtoken = self.auth.refresh(refresh_token=refresh_token)["idToken"]
				self.global_email = self.auth.get_account_info(id_token=self.global_idtoken)["users"][0]["email"]
				self.global_username = self.auth.get_account_info(id_token=self.global_idtoken)["users"][0]["displayName"]

				Clock.schedule_once(lambda dt: self.giris_on(),0.5)

		return Builder.load_file("main.kv")

MainApp().run()
