from kfrm_tool.include.db.db_connection import PostgreSQLConnection
from kfrm_tool.include.File_Class import GetShpProj4
from kfrm_tool.include.setting.logger import KFRMLogger
from kfrm_tool.include.setting.path_list import DefaultPath
from kfrm_tool.include.Util import callExecute


class FileImport:
    def __init__(self):
        self.path = DefaultPath()
        self.pg = PostgreSQLConnection()

        global OGR_PATH, SQLITE_PATH
        OGR_PATH = self.path.getOgr2ogrPath()
        SQLITE_PATH = self.path.getSqliteDBPath()

    def sqliteImport(self, filePath, saveName, encoding="CP949", epsg="EPSG:5179"):
        proj4 = GetShpProj4(filePath)
        if not proj4:
            raise Warning(
                "Please try again after setting the coordinate system of the file."
            )

        arg = f""" "{OGR_PATH}" -f SQLite -dsco SPATIALITE=YES "{SQLITE_PATH}" "{filePath}" -nlt PROMOTE_TO_MULTI 
                    -overwrite --config SHAPE_ENCODING {encoding} -nln "{saveName}" -s_srs "{proj4}" -t_srs {epsg}""".replace(
            "\n", ""
        )
        #         arg = f''' "{OGR_PATH}" -f SQLite -dsco SPATIALITE=YES "{SQLITE_PATH}" "{filePath}" -nlt PROMOTE_TO_MULTI
        #                     -overwrite --config SHAPE_ENCODING {encoding} -nln "{saveName}"'''.replace("\n", "")

        return callExecute(arg)

    def postgisImport(self, filePath, saveName, encoding="EUC_KR"):
        host = self.pg.getHost()
        user = self.pg.getUserName()
        dbName = self.pg.getDbName()
        password = self.pg.getPassword()
        arg = f""" {OGR_PATH} -f "PostgreSQL" "PG:host={host} user={user} dbname={dbName} password={password}" 
            "{filePath}" -lco GEOMETRY_NAME=geometry -nlt PROMOTE_TO_MULTI -nln "{saveName}" 
            --config SHAPE_ENCODING {encoding} -lco precision=NO -overwrite """.replace(
            "\n", ""
        )

        return callExecute(arg)

    def convertPostgisToSqlite(self, sql, saveTableName):
        host = self.pg.getHost()
        user = self.pg.getUserName()
        dbName = self.pg.getDbName()
        password = self.pg.getPassword()
        arg = f""" "{OGR_PATH}" --config PG_LIST_ALL_TABLES YES --config PG_SKIP_VIEWS YES 
            -f SQLITE -overwrite "{SQLITE_PATH}" 
            PG:"host={host} user={user} dbname={dbName} password={password} active_schema=public schemas=public" 
            -sql "{sql}" -dsco SPATIALITE=YES -gt 65536 -nln "{saveTableName}" """.replace(
            "\n", ""
        )

        KFRMLogger.debug(f"convertPostgisToSqlite : {sql}")
        return callExecute(arg)
