import sys
from os import path
from PyQt4 import QtGui, uic
from sympy.solvers import solve
from sympy import Symbol, I, re, im, simplify
from numpy import pi, sqrt


class GuiMain(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = uic.loadUi(path.dirname(path.abspath(__file__)) + '/main.ui', self)
        self.ui.pushButton_calculate.clicked.connect(self.calculate)

    def read_variable(self):
        var_list = []
        if self.ui.checkBox_inductance.isChecked():
            self.L = self.ui.doubleSpinBox_inductance.value() * 10 ** -6
        else:
            self.L = Symbol('L', real=True)
            var_list.append(self.L)
        if self.ui.checkBox_capacitance1.isChecked():
            self.C1 = self.ui.doubleSpinBox_capacitance1.value()
        else:
            self.C1 = Symbol('C1', real=True)
            var_list.append(self.C1)
        if self.ui.checkBox_capacitance2.isChecked():
            self.C2 = self.ui.doubleSpinBox_capacitance2.value()
        else:
            self.C2 = Symbol('C2', real=True)
            var_list.append(self.C2)
        if self.ui.checkBox_frequency.isChecked():
            self.f = self.ui.doubleSpinBox_frequency.value() * 2 * pi
        else:
            self.f = Symbol('f', real=True)
            var_list.append(self.f)
        if self.ui.checkBox_resistance.isChecked():
            self.R = self.ui.doubleSpinBox_resistance.value()
        else:
            self.R = Symbol('R', real=True)
            var_list.append(self.R)

        return var_list

    def calculate(self):
        var_list = self.read_variable()
        if self.ui.radioButton.isChecked():
            self.calculate_rf(var_list)
        elif self.ui.radioButton_2.isChecked():
            self.calculate_rf_adapt1(var_list)
        elif self.ui.radioButton_3.isChecked():
            self.calculate_rf_adapt2(var_list)

    def calculate_rf(self, var_list):
        real = re(I * self.f * self.L + self.R + 1 / (re(self.C1) * self.f * I))
        imaginary = im(I * self.f * self.L + self.R + 1 / (re(self.C1) * self.f * I))
        res = solve([real, imaginary], *var_list)
        print(res)

    def calculate_rf_adapt1(self, var_list):
        real = simplify(re(1 / (1 / (I * self.f * self.L + self.R) + I * self.f * self.C1) - I / (self.f * self.C2)))
        imaginary = im(1 / (1 / (I * self.f * self.L + self.R) + I * self.f * self.C1) - I / (self.f * self.C2))
        res = solve([real - 50, imaginary], *var_list)
        print(res)

    def calculate_rf_adapt2(self, var_list):
        C1 = 1 / (2 * self.f * self.R) * (1 - (1 - 2 * self.R / 50) ** 2) ** 0.5
        C2 = (self.f ** 2 * self.L - (1 - self.R / 50) / C1) ** -1
        print(C1, C2)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = GuiMain()
    myapp.show()
    sys.exit(app.exec_())
