import motorcalc.dcmotor as dcm
import numpy as np
import datetime
from numpy.core.arrayprint import _none_or_positive_arg
from openpyxl import Workbook
from openpyxl.styles import Font
from texttable import Texttable

class CDCMotorExport():
    def __init__(self, dcm:dcm.CDCMotor, filename:str = None):
        self.dcm = dcm
        self.filename = filename

    def list_spec_table(self):
        """
        Prints a specification table to the command line
        """
        t = Texttable()
        t.add_row(["No","Parameter","Unit","Value"])
        t.add_row([1,"Voltage","V",self.dcm.U_N])
        t.add_row([2,"Terminal resistance","Ω",self.dcm.R])
        t.add_row([3, "Terminal inductance", "mH", self.dcm.H])
        t.add_row([4, "No-load speed", "rpm", int(self.dcm.n_0)])
        t.add_row([5, "No-load current", "A", self.dcm.I_0])
        t.add_row([6, "Nominal torque", "mNm", 1000.0*self.dcm.M_WP])
        t.add_row([7, "Nominal speed", "rpm", int(self.dcm.calc_n_from_M(self.dcm.M_WP))])
        t.add_row([8, "Nominal current", "A", self.dcm.calc_I_from_M(self.dcm.M_WP)])
        t.add_row([9, "Max. output power", "W", self.dcm.P_maxpower])        
        t.add_row([10, "Max. efficiency", "%", self.dcm.eta_max*100.0])
        t.add_row([11, "Back-EMF constant", "mV/rpm", self.dcm.k_M*30/np.pi*1000.0])
        t.add_row([12, "Torque constant", "mNm/A", 1000*self.dcm.k_M])
        t.add_row([13, "Speed/torque gradient", "rpm/mNm", self.dcm.n_0/self.dcm.M_S/1000.0])
        t.add_row([14, "Rotor inertia", "gcm^2", self.dcm.Theta])
        # 15 Weight g 21
        # 16 Thermal resistance housing-ambient K/W 8
        # 17 Thermal resistance winding-housing K/W 9.5
        # 18 Thermal time constant motor s 354
        # 19 Thermal time constant winding s 23
        # 20 Operating temperature range °C -40 ~ +120
        # 21 Thermal class of winding °C 155
        # 22 Axial play mm 0.012
        # 23 Radial play mm 0.08
        # 24 Axial load dynamic N 1.5
        # 25 Axial load static N 37
        # 26 Radial load at 3 mm from mounting face N 12
        # 27 No. of pole pairs 4
        # 28 Bearings 2 ball bearings
        # 29 Commutation Sensorless
        # 30 Protection class IP 20
        print(t.draw())


    def export_to_excel(self, filename: str = None):
        """
        Exports the results to excel. Uses the file name given in the member variable self.file_name
        """
        exWB = Workbook()
        ws = exWB.active
        try:
            if self.dcm.motor_name != '':
                ws.title = self.dcm.motor_name
        except:
            pass
        ws.append(["DC Motor Calculation: " + self.dcm.motor_name])
        ws['A1'].font=Font(size=16,bold=True)
        ws.append(["File generated on:", "", datetime.datetime.now().strftime("%d-%b-%y"), datetime.datetime.now().strftime("%H:%M:%S")])
        ws['A2'].font=Font(size=12,bold=True,italic=True)
        ws['B2'].font=Font(size=12,bold=True,italic=True)
        ws.append(["File generated by: KOCO DC-Motor calculator"])
        ws['A3'].font=Font(size=12,bold=True,italic=True)
        ws.append([])

        row=5
        col=1
        titleStr = "Input data DC motor"
        headerStr = ['', 'voltage', 'term. resist.', 'no-load cur.', 'no-load speed', 'torque const.']
        data = [ \
            ['unit', 'Volt', 'Ohm', 'A', 'RPM', 'mNm/A'], \
            ['value', self.dcm.U_N, self.dcm.R, self.dcm.I_0, self.dcm.n_0, self.dcm.k_M] \
            ]
        row, col = self._excel_add_table_to_worksheet(ws, row, col, titleStr, headerStr, data)
        
        row += 1
        col = 1
        titleStr = "DC motor performance data"
        headerStr = ['', 'unit', '@no-load', '@max eff.', '@max power', 'stall']
        data = [ \
            ['speed', 'RPM', self.dcm.n_0, self.dcm.n_meff, self.dcm.calc_n_from_M(self.dcm.M_maxpower),0], \
            ['current', 'A', self.dcm.I_0, self.dcm.I_meff, self.dcm.calc_I_from_M(self.dcm.M_maxpower),self.dcm.I_S], \
            ['torque', 'Nm', self.dcm.M_0, self.dcm.M_meff, self.dcm.M_maxpower,self.dcm.M_S], \
            ['power', 'W', 0, self.dcm.P_meff, self.dcm.P_maxpower,0], \
            ['eff.', '%', 0, self.dcm.eta_max*100.0, self.dcm.calc_eta_from_M(self.dcm.M_maxpower)*100.0,0.0] \
            ]
        row, col = self._excel_add_table_to_worksheet(ws, row, col, titleStr, headerStr, data)
        if not filename:
            filename = self.filename

        if not filename:
            if not self.dcm.motor_name:
                filename = "MotorCalc_output.xlsx"
            else:
                filename = self.dcm.motor_name + ".xlsx"
        exWB.save(filename=filename)
        return(row, col)
    
    def _excel_add_table_to_worksheet(self, ws, row, col, titleStr, headerStr, data):
        ws.cell(row, col, value = titleStr).font = Font(size=12,bold=True)
        row += 1
        for hstr in headerStr:
            ws.cell(row,col,value=hstr).font=Font(bold=True)
            col+=1
        row+=1
        col=1

        for dpoints in data:
            for dp in dpoints:
                ws.cell(row,col,value=dp)
                if col == 1:
                    ws.cell(row,col).font=Font(size=12, bold=True)

                col+=1
            row += 1
            col = 1
        return row,col 


def Main():
    pass

if __name__ == "__main__":
    Main()