#!/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('-i', type=str, help='input shapefile')
parser.add_argument('-o', type=str, help='write release file')
parser.add_argument('-f', type=str, help='field name', default='h')
parser.add_argument('-v', type=str, help='release area value', default='1')
parser.add_argument('-x0', type=str, help='reference point x')
parser.add_argument('-y0', type=str, help='reference point y')
parser.add_argument('-z0', type=str, help='reference point z')
parser.add_argument('-dfdx', type=str, help='increase of f with x')
parser.add_argument('-dfdy', type=str, help='increase of f with y')
parser.add_argument('-dfdz', type=str, help='increase of f with z')
parser.add_argument('-normal', type=str, help='project to normal from vertical (yes/no)', default='yes')
parser.add_argument('-d', type=str, help='default value')
parser.add_argument('-offsetx', type=float, help='offset mesh by x m', default=0)
parser.add_argument('-offsety', type=float, help='offset mesh by y m', default=0)

args = parser.parse_args()



sf = shp.Reader(args.i)


def header(objectName, className='dictionary', locationName="constant"):
    return ("/*--------------------------------*- C++ -*----------------------------------*\\\n"
            "| =========                 |                                                 |\n"
            "| \\\\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox           |\n"
            "|  \\\\    /   O peration     | faSavageHutterFOAM                              |\n"
            "|   \\\\  /    A nd           | Copyright (C) 2017 Matthias Rauter              |\n"
            "|    \\\\/     M anipulation  |                                                 |\n"
            "\*---------------------------------------------------------------------------*/\n"
            "FoamFile\n"
            "{}\n"
            "    version     2.0;\n"
            "    format      ascii;\n"
            "    class       {};\n"
            "    location    \"{}\";\n"
            "    object      {};\n"
            "{}\n"
            "// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //\n"
            ).format("{", className, locationName, objectName, "}");

def footer():
    return ("\n"
            "// ************************************************************************* //\n"
            "\n")



if args.o  is not None:
    fi = open(args.o, 'w')
    fi.write(header("releaseArea", "dictionary"))
    fi.write("\n"
             "fields\n"
             "(\n"
             "    {}\n".format(args.f))
    fi.write("    {\n")
    if args.d is not None:
        fi.write("        default {};\n".format(args.d))
    fi.write("        regions\n"
             "        (\n")

i = 1
for shape in sf.shapeRecords():
    if args.o  is not None:
        fi.write("            releaseArea{}\n".format(i))
        fi.write("            {\n"
				 "		        type polygonlinear;\n")
        fi.write("		        offset ({} {} 0);\n".format(args.offsetx, args.offsety))
        fi.write("		        vertices\n"
				 "		        (\n")

        for p in shape.shape.points[:]:
            fi.write("		            ({} {} {})\n".format(p[0],p[1],0))

        fi.write("		        );\n"
        		 "		        valueAtZero {};\n".format(args.v))
        if args.x0 is not None:
            fi.write("		        x0 {};\n".format(args.x0))    
        if args.y0 is not None:
            fi.write("		        y0 {};\n".format(args.y0))    
        if args.z0 is not None:
            fi.write("		        z0 {};\n".format(args.z0))    
        if args.dfdx is not None:
            fi.write("		        dfdx {};\n".format(args.dfdx))   
        if args.dfdy is not None:
            fi.write("		        dfdy {};\n".format(args.dfdy))   
        if args.dfdz is not None:
            fi.write("		        dfdz {};\n".format(args.dfdz))    
        if args.normal is not None:
            fi.write("		        projectToNormal {};\n".format(args.normal))   

        fi.write("	        }\n")

    i = i+1

if args.o is not None:
	fi.write("        );\n"
			 "    }\n"
			 ");")
