#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# generated by wxGlade 0.9.6 on Thu Oct 29 22:41:10 2020
#

import numpy, matplotlib
if matplotlib.__version__ < '2.2':
    raise ValueError("Minimum Matplotlib version required: 2.2")

#
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas

import wx
import os
#from shutil import make_archive

# read from glade
import gui
# read from main solver
import rigidWink

# excel format
import openpyxl
from openpyxl.utils import get_column_letter # 列幅の指定 2020/05/27

# pdf export
import report
# begin wxGlade: dependencies
# end wxGlade

# begin wxGlade: extracode
# end wxGlade

class MyFrame(gui.MyFrame):


    def write_result_xlsx(self,outputFile):
        # result.xlsx に計算結果を書き込む
        # 戻り値 0: 失敗, 1: 成功
        try:
            wb = openpyxl.Workbook()
            # Model
            ########################################################################
            ws1 = wb.active
            ws1.title = 'MODEL'
            header1 = ['X1, m', 'X2, m', 'Y1, m', 'Y2, m', 'nidmx', 'nidmy', 'kb, kN/m3']
            for i in range(len(header1)):
                ws1.cell(row = 1, column = i + 1).value = header1[i]
            for i in range(0,100):
                value = self.grid_model.GetCellValue(i,0)
                if value != '':
                    for j in range(0,len(header1)):
                        ws1.cell(row=i+2, column = j+1).value = self.grid_model.GetCellValue(i,j)
                else:
                    break
            # 列幅の指定
            """
            ws1.column_dimensions[get_column_letter(1)].width = 10
            for x in range(1, len(header1)):
                ws1.column_dimensions[get_column_letter(x + 1)].width = 15
            """
            ########################################################################
            # LOAD
            ws2 =  wb.create_sheet('LOAD')
            header2 = ['CASE', 'N, kN', 'Mx, kN.m', 'My, kN.m' ]
            for i in range(len(header2)):
                ws2.cell(row = 1, column = i + 1).value = header2[i]
            for i in range(0,100):
                value = self.grid_load.GetCellValue(i,0)
                if value != '':
                    for j in range(0,len(header2)):
                        ws2.cell(row=i+2, column = j+1).value = self.grid_load.GetCellValue(i,j)
                else:
                    break
            # 列幅の指定
            """
            ws2.column_dimensions[get_column_letter(1)].width = 10
            for x in range(1, len(header2)):
                ws2.column_dimensions[get_column_letter(x + 1)].width = 12
            """
            ########################################################################
            # COMB
            ws3 =  wb.create_sheet('COMB')
            header3 = ['LABEL', 'LOAD1', '', 'LOAD2', '', 'LOAD3', '', 'LOAD4', '' ]
            for i in range(len(header3)):
                ws3.cell(row = 1, column = i + 1).value = header3[i]
            for i in range(0,100):
                value = self.grid_comb.GetCellValue(i,0)
                if value != '':
                    for j in range(0,len(header3)):
                        ws3.cell(row=i+2, column = j+1).value = self.grid_comb.GetCellValue(i,j)
                else:
                    break
            ########################################################################
            # ctln
            ########################################################################
            ws4 =  wb.create_sheet('CTLN')
            header4 = ['Title', 'r, Model', 'r, Uplift']
            for i in range(len(header4)):
                ws4.cell(row = 1, column = i + 1).value = header4[i]
            for i in range(0,100):
                value = self.grid_ctln.GetCellValue(i,0)
                if value != '':
                    for j in range(0,len(header4)):
                        ws4.cell(row=i+2, column = j+1).value = self.grid_ctln.GetCellValue(i,j)
                else:
                    break

            wb.save(outputFile)
            return 1
        except Exception as err:
            print(err)
            return 0


    # Export Pdf report
    ########################################################################
    def Export_pdf(self,event):

        with wx.FileDialog(self, "Save Pdf File", wildcard="Input File (*.pdf)|*.pdf",
                           style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as fileDialog:
            if fileDialog.ShowModal() == wx.ID_CANCEL:
                return     # the user changed their mind
            # save the current contents in the file
            pathname = fileDialog.GetPath() # pdf file

            try:
                # テキストの読み込み
                ########################################################################
                #pdfFile = "test.pdf"
                title = self.grid_ctln.GetCellValue(0,0)
                num = self.text_ctrl_total.GetValue()
                num = int(num)+1
                inputf = []
                imagefile = []
                for i in range(0,num):
                    inputf.append("./db/result_" + str(i) + ".txt")
                    imagefile.append("./db/result_" + str(i) + ".png")
                    # イメージファイルの読み込み
                    obj = report.Report()
                    obj.create_pdf(inputf,imagefile,pathname,title)

            except IOError:
                wx.LogError("Cannot save current data in file '%s'." % pathname)

    # Export Excel Sheet
    ########################################################################
    def OnLoad(self,event):
    #def OnSaveAs(self, event):
        with wx.FileDialog(self, "Save Excel File", wildcard="Input File (*.xlsx)|*.xlsx",
                           style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as fileDialog:
            if fileDialog.ShowModal() == wx.ID_CANCEL:
                return     # the user changed their mind
            # save the current contents in the file
            pathname = fileDialog.GetPath()
            try:
                #with open(pathname, 'w') as file:
                    #self.doSaveData(file)
                self.write_result_xlsx(pathname)
            except IOError:
                wx.LogError("Cannot save current data in file '%s'." % pathname)

    """
    pathname = self.showFileDialog()
        #pathname = self.showDialog()
        print("this is the test",pathname)
    """
    # Import Excel Sheet
    ########################################################################
    def OnImport(self, event):
        """
        if self.contentNotSaved:
            if wx.MessageBox("Current content has not been saved! Proceed?", "Please confirm", wx.ICON_QUESTION | wx.YES_NO, self) == wx.NO:
                return
        """
        # otherwise ask the user what new file to open
        with wx.FileDialog(self, "Open Input xlsx file", wildcard="Input files (*.xlsx)|*.xlsx",
                           style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:

            if fileDialog.ShowModal() == wx.ID_CANCEL:
                return     # the user changed their mind

            # Proceed loading the file chosen by the user
            pathname = fileDialog.GetPath()
            try:
                #with open(pathname, 'r') as file:
                #self.doLoadDataOrWhatever(file)
                self.read_data_xlsx(pathname)
            except IOError:
                wx.LogError("Cannot open file '%s'." % newfile)
    """
    def OnImport(self, event):  # wxGlade: MyFrame.<event_handler>
        with wx.FileDialog(self, "Import Excel File",
                           style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as fileDialog:
            if fileDialog.ShowModal() == wx.ID_CANCEL:
                return     # the user changed their mind
            # save the current contents in the file
            pathname = fileDialog.GetPath()
            try:
                self.read_data_xlsx(pathname)
            except IOError:
                wx.LogError("Cannot save current data in file '%s'." % pathname)

        #self.text_ctrl_1.SetValue(pathname)
    """
    def read_data_xlsx(self,inputFile):
        # data.xlsx からデータを読み込む
        # 戻り値 0: 失敗, 1: 成功
        row = 0
        column = 0
        try:
            wb = openpyxl.load_workbook(inputFile)

            ####################
            # Model
            #ws1 = wb.active
            #ws1.title = 'MODEL'
            ws1 = wb['MODEL']
            for i in range(1,100):
                if ws1.cell(row=i+1,column=1).value != None:
                    for j in range(0,7):
                        if ws1.cell(row=i+1,column=j+1).value != None:
                            valuecell = str(ws1.cell(row=i+1,column=j+1).value)
                            self.grid_model.SetCellValue(i-1,j,valuecell)
                            print(valuecell)
                else:
                    break
            ####################
            # LOAD
            #ws2 = wb.active
            #ws2.title = 'LOAD'
            ws2 = wb['LOAD']
            for i in range(1,100):
                if ws2.cell(row=i+1,column=1).value != None:
                    for j in range(0,4):
                        if ws2.cell(row=i+1,column=j+1).value != None:
                            valuecell = str(ws2.cell(row=i+1,column=j+1).value)
                            self.grid_load.SetCellValue(i-1,j,valuecell)
                            print(valuecell)
                else:
                    break
            ####################
            # COMB
            #ws3 = wb.active
            #ws3.title = 'COMB'
            ws3 = wb['COMB']
            for i in range(1,100):
                if ws3.cell(row=i+1,column=1).value != None:
                    for j in range(0,9):
                        if ws3.cell(row=i+1,column=j+1).value != None:
                            valuecell = str(ws3.cell(row=i+1,column=j+1).value)
                            self.grid_comb.SetCellValue(i-1,j,valuecell)
                            print(valuecell)
                else:
                    break

            ####################
            #  CTLN
            ws4 = wb['CTLN']
            for i in range(1,100):
                if ws4.cell(row=i+1,column=1).value != None:
                    for j in range(0,9):
                        if ws4.cell(row=i+1,column=j+1).value != None:
                            valuecell = str(ws4.cell(row=i+1,column=j+1).value)
                            self.grid_ctln.SetCellValue(i-1,j,valuecell)
                            print(valuecell)
                else:
                    break

            return 1
        except Exception as err:
            print(err)
            return 0

    def showFileDialog(self):
        with wx.FileDialog(self, 'Pls, select File',
                          style=wx.DD_DEFAULT_STYLE
                                | wx.DD_DIR_MUST_EXIST
                                | wx.DD_CHANGE_DIR,
                           defaultFile="rigidWink.xls"
                          ) as dialog:
            if dialog.ShowModal() == wx.ID_CANCEL:
                return
            return dialog.GetPath()

    # Sample Data Loading
    ########################################################################
    def OnSample(self,event):

        xx1 = []
        xx2 = []
        yy1 = []
        yy2 = []
        ndimx = []
        ndimy = []
        kb = []

        # make sample model
        xx1.append(0.0)
        xx2.append(100.0)
        yy1.append(0.0)
        yy2.append(30.0)
        ndimx.append(100)
        ndimy.append(30)
        kb.append(50000.0)

        xx1.append(0.0)
        xx2.append(50.0)
        yy1.append(30.0)
        yy2.append(60.0)
        ndimx.append(50)
        ndimy.append(30)
        kb.append(50000.0)

        for i in range(0,len(xx1)):
            self.grid_model.SetCellValue(i,0,str(xx1[i]))
            self.grid_model.SetCellValue(i,1,str(xx2[i]))
            self.grid_model.SetCellValue(i,2,str(yy1[i]))
            self.grid_model.SetCellValue(i,3,str(yy2[i]))
            self.grid_model.SetCellValue(i,4,str(ndimx[i]))
            self.grid_model.SetCellValue(i,5,str(ndimy[i]))
            self.grid_model.SetCellValue(i,6,str(kb[i]))

        # make load data
        case = []
        nn = [] # Axial Force, kN
        mmx = [] # Over Turning Moment, kN.m
        mmy = [] # Over Turning Moment, kN.m
        case.append("L")
        nn.append(1400000.0)
        mmx.append(0.0)
        mmy.append(5000000.0)
        case.append("L1X")
        nn.append(0.0)
        mmx.append(10000000.0)
        mmy.append(0.0)
        case.append("L1Y")
        nn.append(0.0)
        mmx.append(0.0)
        mmy.append(10000000.0)
        for i in range(0,len(case)):
            self.grid_load.SetCellValue(i,0,case[i])
            self.grid_load.SetCellValue(i,1,str(nn[i]))
            self.grid_load.SetCellValue(i,2,str(mmx[i]))
            self.grid_load.SetCellValue(i,3,str(mmy[i]))

        # make compb data
        label = []
        fac1  = []
        case1 = []
        fac2  = []
        case2 = []
        fac3  = []
        case3 = []
        fac4  = []
        case4 = []
        #
        label.append("L/Permanent")
        case1.append("L")
        fac1.append(1.0)
        case2.append("")
        fac2.append("")
        case3.append("")
        fac3.append("")
        case4.append("")
        fac4.append("")
        #
        label.append("L1_X+")
        case1.append("L")
        fac1.append(1.0)
        case2.append("L1X")
        fac2.append(1.0)
        case3.append("")
        fac3.append("")
        case4.append("")
        fac4.append("")
        #
        label.append("L1_45+")
        case1.append("L")
        fac1.append(1.0)
        case2.append("L1X")
        fac2.append(1.0)
        case3.append("L1Y")
        fac3.append(1.0)
        case4.append("")
        fac4.append("")
        #
        label.append("L2_X+")
        case1.append("L")
        fac1.append(1.0)
        case2.append("L1X")
        fac2.append(2.0)
        case3.append("")
        fac3.append("")
        case4.append("")
        fac4.append("")
        #
        label.append("L2_45+")
        case1.append("L")
        fac1.append(1.0)
        case2.append("L1X")
        fac2.append(2.0)
        case3.append("L1Y")
        fac3.append(2.0)
        case4.append("")
        fac4.append("")

        for i in range(0,len(label)):
            self.grid_comb.SetCellValue(i,0,label[i])
            self.grid_comb.SetCellValue(i,1,case1[i])
            self.grid_comb.SetCellValue(i,2,str(fac1[i]))
            self.grid_comb.SetCellValue(i,3,case2[i])
            self.grid_comb.SetCellValue(i,4,str(fac2[i]))
            self.grid_comb.SetCellValue(i,5,case3[i])
            self.grid_comb.SetCellValue(i,6,str(fac3[i]))
            self.grid_comb.SetCellValue(i,7,case4[i])
            self.grid_comb.SetCellValue(i,8,str(fac4[i]))

        # make ctln data
        title = 'Sample project'
        r_model = [] # Plot radius on model diagram
        r_uplift = [] # Plot radius on uplift mark
        r_model.append("1")
        r_uplift.append("0.5")
        for i in range(0,len(r_model)):
            self.grid_ctln.SetCellValue(i,0,title)
            self.grid_ctln.SetCellValue(i,1,r_model[i])
            self.grid_ctln.SetCellValue(i,2,r_uplift[i])

    # Import Read xlsx sheet
    ########################################################################
    def OnChooseTargetFile(self, event):  # wxGlade: MyFrame.<event_handler>
        pathname = self.showFileDialog()
        self.text_ctrl_1.SetValue(pathname)

    def OnChooseOutputFile(self, event):  # wxGlade: MyFrame.<event_handler>
        pathname = self.showFileDialog()
        self.text_ctrl_2.SetValue(pathname)

    def showFileDialog(self):
        with wx.FileDialog(self, 'Pls, select File',
                          style=wx.DD_DEFAULT_STYLE
                                | wx.DD_DIR_MUST_EXIST
                                | wx.DD_CHANGE_DIR
                          ) as dialog:
            if dialog.ShowModal() == wx.ID_CANCEL:
                return
            return dialog.GetPath()

    def OnCancel(self, event):  # wxGlade: MyFrame.<event_handler>
        self.Destroy()

    def OnAbout(self,event):
        comment = 'Welcome to rigid wink!!'
        dlg = wx.MessageDialog(self, 'MIT Licence',
                               'Coded by Tsunoppy',
                               wx.OK | wx.ICON_INFORMATION
                               )
        dlg.ShowModal()
        dlg.Destroy()

    def OnPre(self,event):

        index = self.text_ctrl_index.GetValue()
        index = int(index)-1
        num = self.text_ctrl_total.GetValue()
        num = int(num)
        if index < 0:
            index = int(num)
            self.text_ctrl_index.SetValue(str(index))
        else:
            self.text_ctrl_index.SetValue(str(index))

        # Stress
        data = "db/result_" + str(index) + ".png"
        image = wx.Image(data)
        image = image.Scale(480,480,wx.IMAGE_QUALITY_HIGH)
        bitmap = image.ConvertToBitmap()
        wx.StaticBitmap(self.panel_stress, -1, bitmap, pos=(0,0) )

        """
        # Uplift
        data = "db/uplift_" + str(index) + ".png"
        image = wx.Image(data)
        image = image.Scale(480,480,wx.IMAGE_QUALITY_HIGH)
        bitmap = image.ConvertToBitmap()
        wx.StaticBitmap(self.panel_uplift, -1, bitmap, pos=(0,0) )
        """

        # Summary テキストデータを表示
        data = "db/result_" + str(index) + ".txt"
        f = open(data,'r')
        line = f.read()
        f.close()
        #self.text_ctrl_result.AppendText(line)
        self.text_ctrl_result.ChangeValue(line)

        # Detail テキストデータを表示
        data = "db/detail_" + str(index) + ".txt"
        f = open(data,'r')
        line = f.read()
        f.close()
        self.text_ctrl_detail.ChangeValue(line)

    def OnNext(self,event):
        index = self.text_ctrl_index.GetValue()
        index = int(index)+1
        num = self.text_ctrl_total.GetValue()
        num = int(num)
        if index <= num:
            self.text_ctrl_index.SetValue(str(index))
        else:
            index = int(0)
            self.text_ctrl_index.SetValue(str(0))

        # Stress
        data = "db/result_" + str(index) + ".png"
        image = wx.Image(data)
        image = image.Scale(480,480,wx.IMAGE_QUALITY_HIGH)
        bitmap = image.ConvertToBitmap()
        wx.StaticBitmap(self.panel_stress, -1, bitmap, pos=(0,0) )
        """
        # Uplift
        data = "db/uplift_" + str(index) + ".png"
        image = wx.Image(data)
        image = image.Scale(480,480,wx.IMAGE_QUALITY_HIGH)
        bitmap = image.ConvertToBitmap()
        wx.StaticBitmap(self.panel_uplift, -1, bitmap, pos=(0,0) )
        """

        # Summary テキストデータを表示
        data = "db/result_" + str(index) + ".txt"
        f = open(data,'r')
        line = f.read()
        f.close()
        #self.text_ctrl_result.AppendText(line)
        self.text_ctrl_result.ChangeValue(line)

        # Detail テキストデータを表示
        data = "db/detail_" + str(index) + ".txt"
        f = open(data,'r')
        line = f.read()
        f.close()
        self.text_ctrl_detail.ChangeValue(line)

    # about rigidWink
    ########################################################################
    def OnAbout(self,event):
        message = 'Welcom to rigidWink!!\n'
        message += 'Coded by tsunoppy, 2020, @Tokyo\n'
        message += 'pls, check the link as bellow ^v^!\n'
        message += 'https://tsunoppy/.github.io/simpGet'
        dlg = wx.MessageDialog(self, message,
                               'About RigidWink',
                               wx.OK | wx.ICON_INFORMATION
                               )
        dlg.ShowModal()
        dlg.Destroy()

    def OnRef(self,event):
        message = 'https://tsunoppy/.github.io/simpGet'
        dlg = wx.MessageDialog(self, message,
                               'Reference',
                               wx.OK | wx.ICON_INFORMATION
                               )
        dlg.ShowModal()
        dlg.Destroy()

    # Run Solve
    ########################################################################
    def OnExec(self, event):  # wxGlade: MyFrame.<event_handler>

        obj = rigidWink.Winkler()

        # Read Model
        ####################
        xx1 = []
        xx2 = []
        yy1 = []
        yy2 = []
        ndimx = []
        ndimy = []
        kb = []


        for i in range(0,100):
            value = self.grid_model.GetCellValue(i,0)
            if value != "":
                xx1.append(float(self.grid_model.GetCellValue(i,0)))
                xx2.append(float(self.grid_model.GetCellValue(i,1)))
                yy1.append(float(self.grid_model.GetCellValue(i,2)))
                yy2.append(float(self.grid_model.GetCellValue(i,3)))
                ndimx.append(int(self.grid_model.GetCellValue(i,4)))
                ndimy.append(int(self.grid_model.GetCellValue(i,5)))
                kb.append(float(self.grid_model.GetCellValue(i,6)))
            else:
                #print("model, break")
                break


        # Read LOAD
        ####################
        case = []
        nn = []
        mmx = []
        mmy = []
        for i in range(0,100):
            value = self.grid_load.GetCellValue(i,0)
            if value != "":
                case.append(self.grid_load.GetCellValue(i,0))
                nn.append(float(self.grid_load.GetCellValue(i,1)))
                mmx.append(float(self.grid_load.GetCellValue(i,2)))
                mmy.append(float(self.grid_load.GetCellValue(i,3)))
            else:
                #print("load, break")
                break


        # Read Comb
        ####################
        label = []
        case1 = []
        fac1  = []
        case2 = []
        fac2  = []
        case3 = []
        fac3  = []
        case4 = []
        fac4  = []
        for i in range(0,100):
            value = self.grid_comb.GetCellValue(i,0)
            if value != "":
                label.append(self.grid_comb.GetCellValue(i,0))
                case1.append(self.grid_comb.GetCellValue(i,1))
                fac1.append(self.grid_comb.GetCellValue(i,2))
                case2.append(self.grid_comb.GetCellValue(i,3))
                fac2.append(self.grid_comb.GetCellValue(i,4))
                case3.append(self.grid_comb.GetCellValue(i,5))
                fac3.append(self.grid_comb.GetCellValue(i,6))
                case4.append(self.grid_comb.GetCellValue(i,7))
                fac4.append(self.grid_comb.GetCellValue(i,8))
            else:
                #print("comb, break")
                break

        # Read CTLN
        ####################
        title = self.grid_ctln.GetCellValue(0,0)
        r_model = float(self.grid_ctln.GetCellValue(0,1))
        r_uplift = float(self.grid_ctln.GetCellValue(0,2))

        # organized analysis case
        n = []
        mx = []
        my = []

        totalNum = int(len(label))-1
        self.text_ctrl_total.SetValue(str(totalNum))

        for i in range(0,len(label)):
            n.append(0.0)
            mx.append(0.0)
            my.append(0.0)
            for j in range(0,len(case)):
                if case1[i] == case[j] and case1[i] != "":
                    fac1[i] = float(fac1[i])
                    n[i]  =  n[i] + nn[j] *fac1[i]
                    mx[i] = mx[i] + mmx[j]*fac1[i]
                    my[i] = my[i] + mmy[j]*fac1[i]
                if case2[i] == case[j] and case2[i] != "":
                    fac2[i] = float(fac2[i])
                    n[i]  = n[i]  + nn[j] *fac2[i]
                    mx[i] = mx[i] + mmx[j]*fac2[i]
                    my[i] = my[i] + mmy[j]*fac2[i]
                if case3[i] == case[j] and case3[i] != "":
                    fac3[i] = float(fac3[i])
                    n[i]  = n[i]  + nn[j] *fac3[i]
                    mx[i] = mx[i] + mmx[j]*fac3[i]
                    my[i] = my[i] + mmy[j]*fac3[i]
                if case4[i] == case[j] and case4[i] != "":
                    fac4[i] = float(fac4[i])
                    n[i]  = n[i]  + nn[j] *fac4[i]
                    mx[i] = mx[i] + mmx[j]*fac4[i]
                    my[i] = my[i] + mmy[j]*fac4[i]

        # make outputfile
        savefile = "./db/input.txt"
        lines = "# Model\n"
        lines += "## Coordinate\n"
        lines += "{:>10s}".format(" No., ")
        lines += "{:>12}".format('X1 m,')
        lines += "{:>12}".format('X2 m,')
        lines += "{:>12}".format('Y1 m,')
        lines += "{:>12}".format('Y2 m,')
        lines += "{:>10}".format('-,')
        lines += "{:>10}".format('-,')
        lines += "{:>12}".format('kb kN/m3')
        lines += "\n"
        for i in range(0,len(xx1)):
            lines += "{:10s}".format(" Area" + str(i+1) + ", " )
            lines += "{:10.2f}".format(xx1[i])+", "
            lines += "{:10.2f}".format(xx2[i])+", "
            lines += "{:10.2f}".format(yy1[i])+", "
            lines += "{:10.2f}".format(yy2[i])+", "
            lines += "{:10d}".format(ndimx[i])+", "
            lines += "{:10d}".format(ndimy[i])+", "
            lines += "{:10.2f}".format(kb[i])
            lines += "\n"
        lines += "\n"
        lines += "#Load\n"
        for i in range(0,len(case)):
            lines += '##' + case[i] + ':\n'
            lines += " {:>3}{:>10.2e}".format('N =',nn[i]) + "kN, "
            lines += " {:>3}{:>10.2e}".format('Mx=',mmx[i]) + "kN.m, "
            lines += " {:>3}{:>10.2e}".format('My=',mmy[i]) + "kN.m\n"
        lines += "\n"
        lines += "#Load Combination\n"
        for i in range(0,len(label)):
            lines += '##' + label[i] + '\n'

            if case1[i] != "":
                lines += " {:>2.2f}".format(fac1[i])
                lines += ' x ' + case1[i]
            if case2[i] != "":
                lines += " + {:>2.2f}".format(fac2[i])
                lines += ' x ' + case2[i]
            if case3[i] != "":
                lines += " + {:>2.2f}".format(fac3[i])
                lines += ' x ' + case3[i]
            if case4[i] != "":
                lines += " + {:>2.2f}".format(fac4[i])
                lines += ' x ' + case4[i]


            lines += "\n"
            lines += " {:>3}{:>10.2e}".format('N =',n[i]) + "kN, "
            lines += " {:>3}{:>10.2e}".format('Mx=',mx[i]) + "kN.m, "
            lines += " {:>3}{:>10.2e}".format('My=',my[i]) + "kN.m\n"
        lines += "\n"
        obj.out(savefile,lines)

        # analysis
        ########################################################################

        if obj.getModel(xx1,xx2,yy1,yy2,ndimx,ndimy,kb):
            obj.getG(xx1,xx2,yy1,yy2)
            #obj.viewModel()
            print("Complete Model Making")
            dlg = wx.MessageDialog(self, 'Complete Model Maiking',
                                   'Complete',
                                   wx.OK | wx.ICON_INFORMATION
                                   )
            dlg.ShowModal()
            dlg.Destroy()
        else:
            del obj
            obj = rigidWink.Winkler()
            print("Fail Model Making")

        for i in range(0,len(label)):
            obj.solve(label[i],i,n[i],mx[i],my[i],r_model,r_uplift)

        """
        # モデルをcanvasに表示
        #print(obj.x,obj.y)
        self.matplotlib_axes.scatter(obj.x,obj.y,s=1,color="black")
        self.matplotlib_axes.spines['right'].set_visible(False)
        self.matplotlib_axes.spines['top'].set_visible(False)
        #test
        self.matplotlib_axes.set_aspect('equal')
        self.matplotlib_canvas.draw()
        event.Skip()
        """
        """
        # 画像をパネルに表示
        # Model
        image = wx.Image('db/model.png')
        image = image.Scale(680,480,wx.IMAGE_QUALITY_HIGH)
        bitmap = image.ConvertToBitmap()
        wx.StaticBitmap(self.panel_disp, -1, bitmap, pos=(0,0) )
        """
        # Model
        image = wx.Image('db/model.png')
        image = image.Scale(480,480,wx.IMAGE_QUALITY_HIGH)
        bitmap = image.ConvertToBitmap()
        wx.StaticBitmap(self.panel_model, -1, bitmap, pos=(0,0) )

        # Stress
        image = wx.Image('db/result_0.png')
        image = image.Scale(480,480,wx.IMAGE_QUALITY_HIGH)
        bitmap = image.ConvertToBitmap()
        wx.StaticBitmap(self.panel_stress, -1, bitmap, pos=(0,0) )
        """
        # Uplift
        image = wx.Image('db/uplift_0.png')
        image = image.Scale(480,480,wx.IMAGE_QUALITY_HIGH)
        bitmap = image.ConvertToBitmap()
        wx.StaticBitmap(self.panel_uplift, -1, bitmap, pos=(0,0) )
        """

        # Summary テキストデータを表示
        f = open("./db/result_0.txt",'r')
        line = f.read()
        f.close()
        #self.text_ctrl_result.AppendText(line)
        self.text_ctrl_result.ChangeValue(line)

        # Detail テキストデータを表示
        f = open("./db/detail_0.txt",'r')
        line = f.read()
        f.close()
        self.text_ctrl_detail.ChangeValue(line)

        # Input テキストデータを表示
        f = open("./db/input.txt",'r')
        line = f.read()
        f.close()
        self.text_ctrl_input.ChangeValue(line)

        """
        
        obj = stiff2D.Stiff2D()
        # read data
        if obj.read_data_xlsx(target_file):
            # exe. calculation
            if obj.calc_main():
                # write result
                if obj.write_result_xlsx(output_file):
                    print('Complete')
                    dlg = wx.MessageDialog(self, 'Cal End',
                                           'Complete',
                                           wx.OK | wx.ICON_INFORMATION
                                           )
                    dlg.ShowModal()
                    dlg.Destroy()
                else:
                    print("出力ファイルの書き込みエラー")
                    dlg = wx.MessageDialog(self, 'Erro output',
                                           'Error output',
                                           wx.OK | wx.ICON_ERROR
                                           )
                    dlg.ShowModal()
                    dlg.Destroy()

            else:
                print('実行時エラー : ' + obj.error)

                dlg = wx.MessageDialog(self, 'Erro' + obj.error,
                                       'Error Execution',
                                       wx.OK | wx.ICON_ERROR
                                       )
                dlg.ShowModal()
                dlg.Destroy()

        else:
            print("入力ファイルの読み込みエラー")
            dlg = wx.MessageDialog(self, 'Error read input',
                                   'Read Error',
                                   wx.OK | wx.ICON_ERROR
                                   )
            dlg.ShowModal()
            dlg.Destroy()

        """
    def OnPlot(self, event):  # wxGlade: MyFrame.<event_handler>

        # Make Model
        obj = rigidWink.Winkler()
        # Read Model
        ####################
        xx1 = []
        xx2 = []
        yy1 = []
        yy2 = []
        ndimx = []
        ndimy = []
        kb = []

        for i in range(0,100):
            value = self.grid_model.GetCellValue(i,0)
            if value != "":
                xx1.append(float(self.grid_model.GetCellValue(i,0)))
                xx2.append(float(self.grid_model.GetCellValue(i,1)))
                yy1.append(float(self.grid_model.GetCellValue(i,2)))
                yy2.append(float(self.grid_model.GetCellValue(i,3)))
                ndimx.append(int(self.grid_model.GetCellValue(i,4)))
                ndimy.append(int(self.grid_model.GetCellValue(i,5)))
                kb.append(float(self.grid_model.GetCellValue(i,6)))
            else:
                #print("model, break")
                break
        # Read CTLN
        ####################
        titile = self.grid_ctln.GetCellValue(0,0)
        r_model = float(self.grid_ctln.GetCellValue(0,1))
        r_uplift = float(self.grid_ctln.GetCellValue(0,2))

        if obj.getModel(xx1,xx2,yy1,yy2,ndimx,ndimy,kb):
            obj.getG(xx1,xx2,yy1,yy2)
            obj.viewModel(r_model)
            print("Complete Model Making")
        else:
            del obj
            obj = rigidWink.Winkler()
            print("Fail Model Making")


# end of class MyFrame

class MyApp(wx.App):
    def OnInit(self):
        new_dir_path = './db'
        try:
            os.mkdir(new_dir_path)
        except FileExistsError:
            pass
        self.frame = MyFrame(None, wx.ID_ANY, "")
        self.SetTopWindow(self.frame)
        self.frame.Show()
        return True

# end of class MyApp

if __name__ == "__main__":
    app = MyApp(0)
    app.MainLoop()
