from StoreXLS import DBXLStorage
import os
import UtilPack as util

class PoleXLS(DBXLStorage):
    m_dictSheetInfo = {}
    
    # 여기서부터 이 프로젝트에 특화된 함수
    def checkSheetsInfo(self):
        sheet = self.getSheet(self.xls_infosheet)
        if sheet is None:
            return
        
        # 3번째 줄부터 읽는다. 
        for row in sheet.iter_rows(min_row=3, values_only=True):
            sheetName = row[0]            
            idxList = range(0, len(row))
            listRecp = []
            for colIdx, item in zip(idxList, row):
                # 시트 이름은 넘어가자.
                if 0 == colIdx:
                    continue
                
                self.getSheet(sheetName, True)
                
                text = str(item) if item is not None else ""
                title, recp = util.GetSheetInfoValue(text)
                self.SetCellValueStr(sheetName, colIdx, 1, title)
                listRecp.append(recp)
            
            self.m_dictSheetInfo[sheetName] = listRecp
            
        #print(self.m_dictSheetInfo)


    def FindCloestPole(self, srcLat, srcLon):
        sheet = self.getSheet("PoleInfo")
        if sheet is None:
            return -1, 0
        
        if None == srcLat or None == srcLon:
            return -1, 0
        
        # 헤더 다음 줄부터 읽는다.
        listDistance = []
        for row in sheet.iter_rows(min_row=2, values_only=True):
            strLon = row[6]
            strLat = row[7]
            
            if "None" in strLon or "None" in strLat:
                continue
            
            dist = 0
            if strLon != "" and strLat != "":
                trgLat = float(strLat)
                trgLon = float(strLon)
                dist = util.GetDistanceGPS(srcLat, srcLon, trgLat, trgLon)
                
            listDistance.append(dist)
            
        if 0 >= len(listDistance):
            return -1, 0
        
        min_value = min(listDistance)
        retIdx = listDistance.index(min_value) + 1
        
        return retIdx, round( min_value, 0 )
    

    def GetPoleInfoAll(self, nIdx:int):
        sheet = self.getSheet("PoleInfo")
        if sheet is None:
            return None
        
        retList = []
        retList.append(sheet.cell(row=nIdx,column=1).value)
        retList.append(sheet.cell(row=nIdx,column=2).value)
        retList.append(sheet.cell(row=nIdx,column=3).value)
        retList.append(sheet.cell(row=nIdx,column=4).value)
        retList.append(sheet.cell(row=nIdx,column=5).value)
        retList.append(sheet.cell(row=nIdx,column=6).value)
        
        return retList
    

    def GetPoleInfo(self, nIdx:int, colNum:int):
        sheet = self.getSheet("PoleInfo")
        if sheet is None:
            return None
        
        if 0 >= nIdx or 0 >= colNum:
            return None
        
        return sheet.cell(row=nIdx,column=colNum).value
    

    def AddImgInfo(self, TrgSheetName:str, EXIF_Date:str, EXIF_GPS:str, Path:str):
        sheet = self.getSheet("ImgInfo")
        if sheet is None:
            return -1
        
        # 마지막 행 찾기
        last_row = self.FindLastRow("ImgInfo")
        if 0 > last_row:
            return -1
        
        TrgRow = last_row + 1
        
        sheet.cell(row=TrgRow,column=1,value=TrgSheetName)
        sheet.cell(row=TrgRow,column=2,value=EXIF_Date)
        sheet.cell(row=TrgRow,column=3,value=EXIF_GPS)
        sheet.cell(row=TrgRow,column=4,value=Path) 
        
        return TrgRow
        

    def FindRowCompValue(self, sheetNameTrg:str, nTrgCol:int, valueSrc:str, bCmpFile:bool = False, pathBase:str = ""):
        sheet = self.getSheet(sheetNameTrg)
        if sheet is None:
            return -1
        
        value = valueSrc
        if True == bCmpFile:
            if False == os.path.isabs(valueSrc):
                value = os.path.join(pathBase, valueSrc)

        retIdx = 0
        trgIdx = 0
        for row in sheet.iter_rows(min_row=2, values_only=True):
            valueTrg = row[nTrgCol]

            if valueTrg is None or valueTrg == "":
                continue;

            if True == bCmpFile:
                # 상대경로로 저장했지만 혹시 절대경로 일 수도 있으니...
                if False == os.path.isabs(valueTrg):
                    valueTrg = os.path.join(pathBase, valueTrg)


                if True == os.path.samefile(os.path.normpath(value), os.path.normpath(valueTrg)):
                    retIdx = trgIdx + 1
                    break;
            else:
                if value == valueTrg:
                    retIdx = trgIdx + 1
                    break;

            trgIdx += 1
        
        return retIdx     


    def FindInsertedImgPath(self, pathBase: str, pathImg: str):
        retIdx = self.FindRowCompValue("ImgInfo", 4, pathImg, True, pathBase )
        return retIdx

    # 
    def GetAllRowValue(self, SheetName:str, nRow:int, nColCount:int):
        sheet = self.getSheet(SheetName)
        if sheet is None:
            return None
        
        if 0 >= nRow:
            return None

        if 0 >= nColCount:
            return None
        
        retList = []
        # 엑셀의 컬럼은 1부터 시작하고, 입력받는 값은 컬럼의 개수다. 조심!
        for nCol in range(1, nColCount + 1):
            retList.append(sheet.cell(row=nRow,column=nCol).value)

        return retList
    
            
        


