import sys
import math
import csv
from unittest import skip

lngCol = 9
latCol = 10
filePath = 'culturalFacilityJP_P27_13.csv'
outDir = "tiles"

outFiles = {}

def getLine(f):
  line = f.readline()
  ans = line.strip()
  return (ans)

def getTileNumber(lon, lat):
  tx = math.floor(lon)
  ty = math.floor(lat)
  return (tx, ty)

def main():
  inFile = open(filePath, 'r', encoding='utf-8', newline="")
  cReader = csv.reader(inFile, delimiter=",", quotechar='"')
  schema = getLine(inFile)
  print("schema: ", schema)
  records = 0
  for csvRow in cReader:
    tx, ty = getTileNumber(float(csvRow[lngCol]), float(csvRow[latCol]))
    tname = outDir + "/" + "tile_" + str(tx) + "_" + str(ty) + ".csv"
    if (tname in outFiles):
      outFile = outFiles[tname]
    else:
      outFile = open(tname, "w", encoding="utf-8")
      outFile.write(schema+"\n")
      outFiles[tname] = outFile

    for index, value in enumerate(csvRow):
      csvRow[index]=value.replace(",","_") # 雑な対応
    
    line = ",".join(csvRow)
    outFile.write(line+"\n")

    records = records + 1
  print(records)
  inFile.close()
  for of in outFiles.values():
    of.close()

if __name__ == '__main__':
  args = sys.argv
  if len(args) == 4:
    filePath = args[1]
    lngCol = int(args[2]) 
    latCol = int(args[3])
  main()