class CalculateSalaryWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.__parent = parent
        self.setWindowTitle("Calculate Salary")

        t = datetime.now()
        self.month = QComboBox()
        self.month.addItems([
            "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY",
            "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"
        ])
        self.month.setCurrentIndex(t.month - 1)
        self.year = QSpinBox()
        self.year.setRange(1900, 3000)
        self.year.setValue(t.year)

        self.name = SearchBox(self)
        self.name.setPlaceholderText("Enter Name")

        self.name.returnPressed.connect(self.setIDList)
        self.nameList = []
        self.nameList = DatabaseManager.db.getEmployeeNameList()
        self.name.setList(self.nameList)
        self.name.setCurrentIndex(-1)

        self.id = QComboBox()
        self.id.currentIndexChanged.connect(
            lambda: self.loadInfo(self.id.currentText()))

        self.designation = QLineEdit()
        self.designation.setReadOnly(True)
        self.originalPay = QLineEdit()
        self.originalPay.setReadOnly(True)
        self.originalPayGrade = QLineEdit()
        self.originalPayGrade.setReadOnly(True)
        self.DOJ = QLineEdit()
        self.DOJ.setReadOnly(True)
        self.pan = QLineEdit()
        self.pan.setReadOnly(True)

        self.presentPay = QLineEdit()
        self.presentPay.setReadOnly(True)
        self.da_percent = ValueBox()
        self.hra_percent = ValueBox()
        self.ta_percent = ValueBox()
        self.it_percent = ValueBox()
        self.pt_percent = ValueBox()

        self.name.editTextChanged.connect(self.clearInfo)

        self.bttnCalculate = QPushButton("Calculate")
        self.bttnCalculate.clicked.connect(self.calculate)
        self.bttnCancel = QPushButton("Back")
        self.bttnCancel.clicked.connect(self.goBack)
        self.bttnCalculate.setObjectName("OkButton")
        self.bttnCancel.setObjectName("CancelButton")

        self.setupUI()

    def calculate(self):
        if "" in (self.id.currentText(), self.name.text(),
                  self.designation.text(), self.originalPay.text(),
                  self.originalPayGrade.text(), self.DOJ.text(),
                  self.pan.text(), self.da_percent.text(),
                  self.hra_percent.text(), self.ta_percent.text(),
                  self.it_percent.text(), self.pt_percent.text()):
            msg = QMessageBox(QMessageBox.Information,
                              "Error",
                              "Please enter all the information!",
                              parent=self)
            msg.exec_()
        else:
            if self.__parent is not None:
                self.__parent.gotoPage(
                    "Result",
                    (self.id.currentText(), self.name.text(),
                     self.designation.text(), self.originalPay.text(),
                     self.originalPayGrade.text(), self.DOJ.text(),
                     self.pan.text(), self.da_percent.text(),
                     self.hra_percent.text(), self.ta_percent.text(),
                     self.it_percent.text(), self.pt_percent.text(),
                     self.month.currentText(), self.year.text()))

    def clearInfo(self):
        self.id.setCurrentIndex(-1)
        self.designation.clear()
        self.originalPay.clear()
        self.originalPayGrade.clear()
        self.DOJ.clear()
        self.pan.clear()
        self.da_percent.clear()
        self.hra_percent.clear()
        self.ta_percent.clear()
        self.it_percent.clear()
        self.pt_percent.clear()

    def loadInfo(self, id):
        print "id =", id, "...", len(id)
        if id != '':
            info = DatabaseManager.db.getEmployeeInfo(id)
            _, _, designation, originalPay, originalPayGrade, doj, pan = info
            self.designation.setText(str(designation))
            self.originalPay.setText(str(originalPay))
            self.originalPayGrade.setText(str(originalPayGrade))
            self.DOJ.setText("%02d/%02d/%4d" % (doj.day, doj.month, doj.year))
            self.pan.setText(str(pan))

            _, da, hra, ta, it, pt = DatabaseManager.db.getDesignationInfo(
                designation)

            self.da_percent.setText(str(da))
            self.hra_percent.setText(str(hra))
            self.ta_percent.setText(str(ta))
            self.it_percent.setText(str(it))
            self.pt_percent.setText(str(pt))

    def setIDList(self, name):
        self.id.clear()
        self.id.addItems(DatabaseManager.db.getIdListForName(name))

    def goBack(self):
        if self.__parent is not None:
            self.__parent.goBack()

    def setupUI(self):

        layout = QVBoxLayout()
        layout.setContentsMargins(20, 20, 20, 10)

        datelayout = QHBoxLayout()
        datelayout.addWidget(QLabel("Salary for month of "))
        datelayout.addWidget(self.month)
        datelayout.addWidget(self.year)
        datelayout.addStretch()
        layout.addLayout(datelayout)

        form = QFormLayout()
        form.setSpacing(10)
        form.addRow(QLabel("Name"), self.name)
        form.addRow(QLabel("ID No."), self.id)
        form.addRow(QLabel("Designation"), self.designation)
        form.addRow(QLabel("Original Pay"), self.originalPay)
        form.addRow(QLabel("Original Pay Grade"), self.originalPayGrade)
        form.addRow(QLabel("Date of joining"), self.DOJ)
        form.addRow(QLabel("Pan No."), self.pan)

        infoGroup = QGroupBox("Basic Info")
        infoGroup.setLayout(form)
        layout.addWidget(infoGroup)

        leftForm = QFormLayout()
        leftForm.addRow(QLabel("Dearness Allowance"), self.da_percent)
        leftForm.addRow(QLabel("Housing Rent Allowance"), self.hra_percent)
        leftForm.addRow(QLabel("Transport Allowance"), self.ta_percent)

        leftGroup = QGroupBox("Allowances")
        leftGroup.setLayout(leftForm)

        rightForm = QFormLayout()
        rightForm.addRow(QLabel("Income Tax"), self.it_percent)
        rightForm.addRow(QLabel("Profession Tax"), self.pt_percent)

        rightGroup = QGroupBox("Deductions")
        rightGroup.setLayout(rightForm)

        table = QHBoxLayout()
        table.addWidget(leftGroup)
        table.addWidget(rightGroup)

        layout.addLayout(table)

        layout.addStretch()
        bttnLayout = QHBoxLayout()
        bttnLayout.addStretch()
        bttnLayout.addWidget(self.bttnCancel)
        bttnLayout.addWidget(self.bttnCalculate)

        layout.addLayout(bttnLayout)
        self.setLayout(layout)
class DelEmployeeWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(DelEmployeeWidget, self).__init__(parent)
        self.__parent = parent
        self.setWindowTitle("Delete Employee")
        self.idList = []

        nameList = DatabaseManager.db.getEmployeeNameList()
        self.name = SearchBox(self, nameList)
        self.name.setPlaceholderText("Enter Name")

        self.name.returnPressed.connect(self.setIdList)

        self.id = QtGui.QComboBox()
        self.id.currentIndexChanged.connect(lambda: self.updateInformation(self.id.currentText()))

        self.designation = QtGui.QLineEdit()
        self.designation.setReadOnly(True)
        self.joinDate = QtGui.QLineEdit()
        self.joinDate.setReadOnly(True)
        self.panNo = QtGui.QLineEdit()
        self.panNo.setReadOnly(True)

        self.remove = QtGui.QPushButton("Remove Employee")
        self.remove.clicked.connect(self.removeEmployee)
        self.remove.setObjectName("CancelButton")

        self.back = QtGui.QPushButton("Back")
        self.back.clicked.connect(self.goBack)
        self.back.setObjectName("OkButton")

        self.createWindowLayout()

    def loadNameList(self):
        self.name = SearchBox(self, DatabaseManager.db.getEmployeeNameList())


    def setIdList(self, name):
        self.id.clear()
        self.id.addItems(DatabaseManager.db.getIdListForName(name))

    def goBack(self):
        if self.__parent is not None:
            self.__parent.goBack()

    def updateInformation(self, id):

        info = DatabaseManager.db.getEmployeeInfo(id)
        if info is None:
            self.designation.clear()
            self.joinDate.clear()
            self.panNo.clear()
        else:
            id, name, des, opa, opag, doj, pan = info
            self.designation.setText(des)
            self.joinDate.setText("%02d/%02d/%04d" % (doj.day, doj.month, doj.year))
            self.panNo.setText(pan)

    def createWindowLayout(self):

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.setContentsMargins(20, 20, 20, 20)

        formLayout = QtGui.QFormLayout()
        formLayout.setSpacing(20)

        formLayout.addRow(QtGui.QLabel("Name"), self.name)
        formLayout.addRow(QtGui.QLabel("Employee ID"), self.id)
        formLayout.addRow(QtGui.QLabel("Designation"), self.designation)
        formLayout.addRow(QtGui.QLabel("Date of join"), self.joinDate)
        formLayout.addRow(QtGui.QLabel("Pan No"), self.panNo)

        mainLayout.addLayout(formLayout)

        bttnLayout = QtGui.QHBoxLayout()
        bttnLayout.addStretch()
        bttnLayout.addWidget(self.back)
        bttnLayout.addWidget(self.remove)
        mainLayout.addLayout(bttnLayout)

        self.setLayout(mainLayout)

    def removeEmployee(self):

        if str(self.id.currentText()) == "":
            msg = QtGui.QMessageBox(QtGui.QMessageBox.Information, "Error!!!", "First enter all the information", parent=self)
            msg.exec_()
        else:
            choice = QtGui.QMessageBox.question(self, 'Remove Confirmation!!!',
                                                "Are you sure you want to delete this employee?\nName: " + str(
                                                    self.name.text()) + "\nID: " +
                                                    self.id.currentText() + "\nDesignation: " + str(
                                                    self.designation.text()),
                                                QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
            if choice == QtGui.QMessageBox.Yes:
                try:
                    DatabaseManager.db.delEmployee(self.id.currentText(), self.name.text())
                    msg = QtGui.QMessageBox(QtGui.QMessageBox.NoIcon, "Success", "Deleted Successfully", parent=self)
                    msg.exec_()
                    # reload name list
                    self.name.clear()
                    nameList = DatabaseManager.db.getEmployeeNameList()
                    self.name.addItems(nameList)
                    self.name.setCurrentIndex(-1)

                except Exception as e:
                    raise e
class DelEmployeeWidget(QtGui.QWidget):
    """PySide widget that contains GUI for deleting existing employee from the database

    Contains a ``SearchBox`` for selecting name of employee to be deleted. Selecting the name
    automatically loads IDs of all employees with that name (in case multiple employees have exact same name) in
    a dropdown box (``QComboBox``). After selecting the required ID from there, the employee info
    is automatically loaded.

    Clicking on 'Remove Employee' button prompts the user with a confirmation box. Clicking yes leads to deletion
    of the employee record of from the database. This is done using the ``delEmployee()`` function from DatabaseManager.

    See Also:
        - :py:mod:`SearchBox <CustomWidgets.searchBox.SearchBox>` widget from CustomWidgets
        - :py:meth:`delEmployee() <DatabaseManager.databaseManager.DatabaseManager.delEmployee>` method of DatabaseManager

    """
    def __init__(self, parent=None):
        super(DelEmployeeWidget, self).__init__(parent)
        self.__parent = parent
        self.title = "Delete Employee"
        self.idList = []

        nameList = Database.getdb().getEmployeeNameList()
        self.name = SearchBox(self, nameList)
        self.name.setPlaceholderText("Enter Name")

        self.name.returnPressed.connect(self.setIdList)

        self.id = QtGui.QComboBox()
        self.id.currentIndexChanged.connect(lambda: self.updateInformation(self.id.currentText()))

        self.designation = QtGui.QLineEdit()
        self.designation.setReadOnly(True)
        self.joinDate = QtGui.QLineEdit()
        self.joinDate.setReadOnly(True)
        self.panNo = QtGui.QLineEdit()
        self.panNo.setReadOnly(True)

        self.remove = QtGui.QPushButton("Remove Employee")
        self.remove.clicked.connect(self.removeEmployee)
        self.remove.setObjectName("CancelButton")

        self.back = QtGui.QPushButton("Back")
        self.back.clicked.connect(self.goBack)
        self.back.setObjectName("OkButton")

        self.setupUI()

    # def loadNameList(self):
    #     self.name = SearchBox(self, Database.getdb().getEmployeeNameList())


    def setIdList(self, name):
        """Loads IDs of all employees with given name into the ID dropdown box

        This function is automatically called after selecting a name from the GUI

        Args:
            name (str): Name of employee
        """
        self.id.clear()
        self.id.addItems(Database.getdb().getIdListForName(name))

    def goBack(self):
        if self.__parent is not None:
            self.__parent.goBack()

    def updateInformation(self, id):
        """Loads info for given ID in the GUI boxes. This automatically called on selecting an ID from GUI

        Args:
            id (str): ID of employee who's info needs to be loaded
        """

        emp = Database.getdb().getEmployeeInfo(id)
        if emp is None:
            self.designation.clear()
            self.joinDate.clear()
            self.panNo.clear()
        else:
            self.designation.setText(emp.designation)
            self.joinDate.setText(emp.getStrDate())
            self.panNo.setText(emp.pan)

    def setupUI(self):
        """Arranges GUI elements inside the widget properly"""

        paneLayout = QtGui.QHBoxLayout()
        paneLayout.setContentsMargins(0, 0, 0, 0)

        leftPane = QtGui.QFrame()
        leftPane.setObjectName("leftPane")

        leftPaneLayout = QtGui.QVBoxLayout()
        leftPaneLayout.setContentsMargins(20, 20, 20, 10)
        heading = QtGui.QLabel("Select Employee: ")
        heading.setObjectName("heading")
        leftPaneLayout.addWidget(heading)
        leftPaneLayout.addSpacing(10)

        leftForm = QtGui.QFormLayout()
        leftForm.addRow(QtGui.QLabel("Name"), self.name)
        leftForm.addRow(QtGui.QLabel("Employee ID"), self.id)
        leftPaneLayout.addLayout(leftForm)
        leftPaneLayout.addStretch()
        leftPane.setLayout(leftPaneLayout)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.setContentsMargins(20, 20, 20, 20)

        infoGroup = QtGui.QGroupBox("Basic Info:")
        formLayout = QtGui.QFormLayout()
        formLayout.setContentsMargins(10, 10, 10, 30)
        formLayout.setSpacing(20)

        # formLayout.addRow(QtGui.QLabel("Name"), self.name)
        # formLayout.addRow(QtGui.QLabel("Employee ID"), self.id)
        formLayout.addRow(QtGui.QLabel("Designation"), self.designation)
        formLayout.addRow(QtGui.QLabel("Date of join"), self.joinDate)
        formLayout.addRow(QtGui.QLabel("Pan No"), self.panNo)


        infoGroup.setLayout(formLayout)


        mainLayout.addWidget(infoGroup)
        mainLayout.addStretch()

        bttnLayout = QtGui.QHBoxLayout()
        bttnLayout.addStretch()
        bttnLayout.addWidget(self.back)
        bttnLayout.addWidget(self.remove)
        mainLayout.addLayout(bttnLayout)

        paneLayout.addWidget(leftPane)
        paneLayout.addLayout(mainLayout)
        self.setLayout(paneLayout)

    def removeEmployee(self):
        """Automatically called on clicking 'Remove Employee' button"""

        if str(self.id.currentText()) == "":
            msg = QtGui.QMessageBox(QtGui.QMessageBox.Information, "Error!!!", "First enter all the information", parent=self)
            msg.exec_()
        else:
            choice = QtGui.QMessageBox.question(self, 'Remove Confirmation!!!',
                                                "Are you sure you want to delete this employee?\nName: " + str(
                                                    self.name.text()) + "\nID: " +
                                                    self.id.currentText() + "\nDesignation: " + str(
                                                    self.designation.text()),
                                                QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
            if choice == QtGui.QMessageBox.Yes:
                try:
                    Database.getdb().delEmployee(self.id.currentText())
                    msg = QtGui.QMessageBox(QtGui.QMessageBox.NoIcon, "Success", "Deleted Successfully", parent=self)
                    msg.exec_()
                    # reload name list
                    self.name.clear()
                    nameList = Database.getdb().getEmployeeNameList()
                    self.name.addItems(nameList)
                    self.name.setCurrentIndex(-1)

                except Exception as e:
                    raise e