# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'property_avprice_graph.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox
from pyqtgraph import PlotWidget, plot, DateAxisItem
import pyqtgraph as pg
import sys, os
from scripts import storage
from datetime import datetime
import properties, prop_av_table, main

class TimeAxisItem(pg.AxisItem):
    def tickStrings(self, values, scale, spacing):
        return [datetime.fromtimestamp(value) for value in values]



class Ui_GraphWindow(object):

    def get_cities(self):
        return storage.get_all_cities()

    def populate_graph(self, *args):
        print("city in citylist drop down is:")
        # print(self.citylist.currentText())

        if type(args[0]) == int: # why DOES args return an integer? is it the index? why does it return that?
            city = self.citylist.currentText()
            print("args is an INTEGER, so city is: " + str(city))
        else:
            city = args[0]
            print("args is a STRING, so city is: " + args[0])

        print(f"Fetching {city} from DB")
        print("selected city:")
        print(city)
        data = storage.view_property_data(city)
        print("graph file city:")
        print(data)
        if data == 'not found':
            step=100
            self.title.setText(f"{city.upper()} data not in in database")
            self.graph.clear()

        else:
            self.graph.clear()
                
            print(data)

            dates = []
            avprices = []
            numbeds = []

            
            for entry in data:
                # date = entry[1]
                date = datetime.strptime(entry[1], "%Y-%m-%d_%H:%M")
                # date = QtCore.QTime
                # date = entry[1].replace("-", "")
                # date = date.replace("_", "")
                # date = date.replace(":", "")
                dates.append(date.timestamp())
                avprices.append(float(entry[2]))
                numbeds.append(float(entry[3]))
            print("graphdata")
            print(dates)
            print(avprices)
            print(numbeds)


            self.title.setText(f"{city.upper()} ask price trend")
            pen = pg.mkPen(width=2)
            self.graph.plot([d for d in dates], avprices, pen=pen, symbol="+", symbolSize = 15)
            # axisItems = {'bottom': date_axis}, 

    def city_from_table(self, city):
        print(city)
        print(city + "ok we can call this function from another script. Now how do we populate the graph")
        # but the below function doest work
        # it insists that graph window doesnt have "graph"
        Ui_GraphWindow.populate_graph(Ui_GraphWindow, city)



    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(826, 554)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        # self.change_me_to_plot = QtWidgets.QListWidget(self.centralwidget)
        # self.change_me_to_plot.setGeometry(QtCore.QRect(0, 40, 611, 451))
        # self.change_me_to_plot.setObjectName("change_me_to_plot")

        self.date_axis = TimeAxisItem(orientation="bottom") # necessary to show date instead of a weird number
        self.graph = pg.PlotWidget(self.centralwidget, axisItems = {'bottom': self.date_axis})
        self.graph.setGeometry(QtCore.QRect(0, 40, 611, 451))
        self.graph.setObjectName("Price Trend")
        self.graph.setLabel("left", "Average Ask Price")
        self.graph.setLabel("bottom", "Date")
        self.graph.showGrid(x=True, y=True)

        cities = self.get_cities()
        self.citylist = QtWidgets.QComboBox(self.centralwidget)
        self.citylist.setGeometry(QtCore.QRect(630, 60, 181, 31))
        self.citylist.setObjectName("citylist")
        for city in cities:
            self.citylist.addItem(city)
        self.citylist.activated.connect(self.populate_graph)

        self.citylabel = QtWidgets.QLabel(self.centralwidget)
        self.citylabel.setGeometry(QtCore.QRect(630, 30, 181, 31))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.citylabel.setFont(font)
        self.citylabel.setAlignment(QtCore.Qt.AlignCenter)
        self.citylabel.setObjectName("citylabel")

        self.table_button = QtWidgets.QPushButton(self.centralwidget)
        self.table_button.setGeometry(QtCore.QRect(670, 110, 101, 31))
        self.table_button.setObjectName("table_button")

        self.title = QtWidgets.QLabel(self.centralwidget)
        self.title.setGeometry(QtCore.QRect(140, 10, 251, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.title.setFont(font)
        self.title.setAlignment(QtCore.Qt.AlignCenter)
        self.title.setObjectName("title")

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 826, 21))
        self.menubar.setObjectName("menubar")

        self.menuMenu = QtWidgets.QMenu(self.menubar)
        self.menuMenu.setObjectName("menuMenu")

        self.menuPrograms = QtWidgets.QMenu(self.menubar)
        self.menuPrograms.setObjectName("menuPrograms")

        self.menuProperty_Data = QtWidgets.QMenu(self.menuPrograms)
        self.menuProperty_Data.setObjectName("menuProperty_Data")

        # self.menuAPI = QtWidgets.QMenu(self.menubar)
        # self.menuAPI.setObjectName("menuAPI")

        # self.menuComputer = QtWidgets.QMenu(self.menubar)
        # self.menuComputer.setObjectName("menuComputer")
        MainWindow.setMenuBar(self.menubar)

        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.actionExit = QtWidgets.QAction(MainWindow)
        self.actionExit.setObjectName("actionExit")
        self.actionExit.triggered.connect(self.exit_program)

        # self.actionNews_Scraper = QtWidgets.QAction(MainWindow)
        # self.actionNews_Scraper.setObjectName("actionNews_Scraper")
        # self.actionPolscraper = QtWidgets.QAction(MainWindow)
        # self.actionPolscraper.setObjectName("actionPolscraper")
        # self.actionDarkSky_Weather = QtWidgets.QAction(MainWindow)
        # self.actionDarkSky_Weather.setObjectName("actionDarkSky_Weather")
        # self.actionLocal_Information = QtWidgets.QAction(MainWindow)
        # self.actionLocal_Information.setObjectName("actionLocal_Information")
        # self.actionLock = QtWidgets.QAction(MainWindow)
        # self.actionLock.setObjectName("actionLock")

        self.actionPrice_Display = QtWidgets.QAction(MainWindow)
        self.actionPrice_Display.setObjectName("actionPrice_Display") # is actually property main
        self.actionPrice_Display.triggered.connect(self.toPropertyMain)
        self.actionPrice_Data = QtWidgets.QAction(MainWindow)
        self.actionPrice_Data.setObjectName("actionPrice_Data")
        self.actionPrice_Data.triggered.connect(self.toPriceData)

        self.menuMenu.addAction(self.actionExit)
        self.menuPrograms.addAction(self.actionPrice_Display)
        self.menuPrograms.addAction(self.actionPrice_Data)
        # self.menuPrograms.addAction(self.actionNews_Scraper)
        # self.menuPrograms.addAction(self.menuProperty_Data.menuAction())
        # self.menuPrograms.addAction(self.actionPolscraper)
        # self.menuAPI.addAction(self.actionDarkSky_Weather)
        # self.menuAPI.addAction(self.actionLocal_Information)
        # self.menuComputer.addAction(self.actionLock)
        self.menubar.addAction(self.menuMenu.menuAction())
        self.menubar.addAction(self.menuPrograms.menuAction())
        # self.menubar.addAction(self.menuAPI.menuAction())
        # self.menubar.addAction(self.menuComputer.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Trend Graph"))
        self.citylabel.setText(_translate("MainWindow", "Select City"))
        self.table_button.setText(_translate("MainWindow", "View Table"))
        self.title.setText(_translate("MainWindow", "Property Trend Data"))
        self.menuMenu.setTitle(_translate("MainWindow", "Menu"))
        self.menuPrograms.setTitle(_translate("MainWindow", "Property"))
        # self.menuProperty_Data.setTitle(_translate("MainWindow", "Property Data"))
        # self.menuAPI.setTitle(_translate("MainWindow", "API"))
        # self.menuComputer.setTitle(_translate("MainWindow", "Computer"))
        self.actionExit.setText(_translate("MainWindow", "Exit"))
        # self.actionNews_Scraper.setText(_translate("MainWindow", "News Scraper"))
        # self.actionPolscraper.setText(_translate("MainWindow", "Polscraper"))
        # self.actionDarkSky_Weather.setText(_translate("MainWindow", "DarkSky Weather"))
        # self.actionLocal_Information.setText(_translate("MainWindow", "Local Information"))
        # self.actionLock.setText(_translate("MainWindow", "Lock"))
        self.actionPrice_Display.setText(_translate("MainWindow", "Property Main"))
        self.actionPrice_Data.setText(_translate("MainWindow", "Price Data"))

    
    def toMainMenu(self):
        print("to main menu")
        self.main_menu=QtWidgets.QMainWindow()
        self.ui = main.Ui_MainWindow()
        self.ui.setupUi(self.main_menu)
        MainWindow.destroy()
        self.main_menu.show()
    def toPropertyMain(self):
        print("to main menu")
        self.main_menu=QtWidgets.QMainWindow()
        self.ui = properties.Ui_PropertyWindow()
        self.ui.setupUi(self.main_menu)
        MainWindow.destroy()
        self.main_menu.show()
    def toPriceData(self):
        print("to price data")
        self.price_data=QtWidgets.QMainWindow()
        self.ui = prop_av_table.Ui_TableWindow()
        self.ui.setupUi(self.price_data)
        MainWindow.destroy()
        self.price_data.show()
    def exit_program(self):
        cfm = QMessageBox()
        cfm.setWindowTitle("Close PCP?")
        cfm.setText("Confirm if you want to close the Python Control Panel")
        cfm.setIcon(QMessageBox.Information)
        cfm.setStandardButtons(QMessageBox.Close | QMessageBox.Cancel)
        cfm.setDefaultButton(QMessageBox.Cancel)

        cfm.buttonClicked.connect(self.closeprogram)
        x = cfm.exec_()

    def closeprogram(self, i):
        order = i.text()
        if order == 'Close':
            exit()
        else:
            print(i.text())

app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_GraphWindow()
ui.setupUi(MainWindow)
# Ui_MainWindow.city_from_table()
# if __name__ == "__main__":
#     import sys
#     app = QtWidgets.QApplication(sys.argv)
#     MainWindow = QtWidgets.QMainWindow()
#     ui = Ui_MainWindow()
#     ui.setupUi(MainWindow)
#     MainWindow.show()
#     sys.exit(app.exec_())
