#!/usr/bin/env python 

'''
License
    This file is part of foam-extend.

    foam-extend is free software: you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by the
    Free Software Foundation, either version 3 of the License, or (at your
    option) any later version.

    foam-extend is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with foam-extend.  If not, see <http://www.gnu.org/licenses/>.

Author
    Matthias Rauter matthias.rauter@uibk.ac.at
'''


# these 3 lines make python2 compatible with python3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import argparse
import time
import sys
import shapefile as shp

parser = argparse.ArgumentParser(description='')

parser.add_argument('-meshFile', type=str, help='input meshfile (only for cells) (as csv, use faMeshtoAscii)')
parser.add_argument('-fieldsFile', type=str, help='input fieldsfile (as csv, use faFieldstoAscii)')
parser.add_argument('-asPoints', help='export points in area centers instead of cells', action="store_true")
parser.add_argument('-o', type=str, help='output destination')

args = parser.parse_args()

if args.asPoints:
    w = shp.Writer(shp.POINT)
else:
    w = shp.Writer(shp.POLYGON)

lines = []

if args.asPoints:
    dat = open(args.fieldsFile)
    header = dat.readline()

    while True:
        line=dat.readline()
        if not line: break
        lines.append(line)
        xy = map(float, line.rstrip().split(";"))
        w.point(xy[0], xy[1])

    dat.close()
else:
    dat = open(args.meshFile, 'r')

    for line in dat:
    	lines.append([])
    	parts = line.split(";")
    	for i in range(len(parts)//3):
    		lines[-1].append([float(parts[i*3]), float(parts[i*3+1])])
    	lines[-1].append([float(parts[0]), float(parts[1])])
    	w.poly(parts=[lines[-1]])

    dat.close()
fielddat = open(args.fieldsFile)

w.field('id','C')

header = fielddat.readline().rstrip().split(";")
print("header is \"{}\"".format(header))

for h in header:
	w.field(h, 'F')

for i in range(len(lines)):
    w.record(i, *tuple(map(float, fielddat.readline().rstrip().split(";"))))

w.save(args.o)

