import csv
import os
import shutil

import xlwt

from kfrm_tool.include.setting.path_list import DefaultPath
from kfrm_tool.include.Util import callExecute


class FileExport:
    def __init__(self):
        self.pathList = DefaultPath()

    #         self.sqliteDao = SqliteQuery()

    def copyCsv(self, oriFile, savePath):
        shutil.copyfile(oriFile, savePath)

    def tableExportToCsv(self, tbl, savePath, first=-1, last=-1, fileEncoding="cp949"):
        row = tbl.rowCount()
        col = tbl.columnCount()

        with open(savePath, "w", encoding=fileEncoding, newline="") as f:
            wr = csv.writer(f)
            rowLine = [tbl.horizontalHeaderItem(i).text() for i in range(col)]
            wr.writerow(rowLine)

            for r in range(row):
                rowLine = []
                for c in range(col):
                    itemText = tbl.item(r, c).text()
                    rp = itemText.replace(",", "")

                    if first <= c and c <= last:
                        if rp.replace(".", "").isdigit():
                            itemText = rp
                        else:
                            itemText = "0"
                    else:
                        if rp.replace(".", "").isdigit():
                            itemText = rp

                    rowLine.append(itemText)
                wr.writerow(rowLine)

    # ogr2ogr.exe 프로그램을 사용하여 결과 테이블의 모든 정보를 검색하고 shape 파일로 출력.
    def dataExporToShape(
        self, savePath, tableName, column="*", encoding="CP949", overlap=True
    ):
        if overlap:
            savePath = self.overlapFileName(savePath)
        ogrPath = self.pathList.getOgr2ogrPath()
        dbPath = self.pathList.getSqliteDBPath()

        arg = (
            f'"{ogrPath}" -f "ESRI Shapefile" "{savePath}" "{dbPath}" '
            + f"-sql \"SELECT {column} FROM '{tableName}'\" --config SHAPE_ENCODING {encoding} -lco ENCODING={encoding}"
        )

        return callExecute(arg)

    def dataExportToExcel(self, savePath, shtNames, contents, fileEncoding="UTF-8"):
        savePath = self.overlapFileName(savePath)
        wb = xlwt.Workbook(encoding=fileEncoding)

        for i, sht in enumerate(shtNames):
            ws = wb.add_sheet(sht)

            for j, con in enumerate(contents[i]):
                for k, rw in enumerate(con):
                    ws.write(j, k, rw)

        wb.save(savePath)

    #     def dataExportToCsv(self, tableName, savePath, fileEncoding="UTF-8"):
    #         headers = self.sqliteDao.getTableHeader(tableName)
    #         contents = self.sqliteDao.getTableContents(tableName)
    #
    #         with open(savePath, "w", encoding=fileEncoding, newline='') as f:
    #             wr = csv.writer(f)
    #             wr.writerow(headers)
    #
    #             for r in contents:
    #                 wr.writerow(r)

    def overlapFileName(self, path):
        osIsfile = os.path.isfile
        osSplit = os.path.split
        osSpliText = os.path.splitext

        if osIsfile(path):
            flag = True
            j = 1
            while flag:
                j += 1
                folder, filename = osSplit(path)
                filename, extension = osSpliText(filename)

                splitCount = len(str(j)) + 3
                splitName = f" ({str(j)})"
                if filename[-splitCount:] == splitName:
                    filename = filename[:-splitCount]

                rePath = f"{folder}/{filename}{splitName}{extension}"

                if not osIsfile(rePath):
                    path = rePath
                    flag = False

        return path
