#!/usr/bin/python3

import os
import argparse
import shutil
import tempfile
from gmapsbounds import obj
from gmapsbounds import utils

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("input_filename", help="File name containing geographic locations")
    parser.add_argument('-o', "--output_loc",
        help="Location of program output. Specifies a file name if ends with .kml, otherwise"
        " specifies a directory", default=os.getcwd())
    args = parser.parse_args()
    location_objects = []
    file_empty = True
    save_dir = tempfile.mkdtemp()
    try:
        with open(args.input_filename) as f:
            for location_name in f:
                if location_name != '\n':
                    if file_empty:
                        driver = utils.launch_driver()
                        file_empty = False
                    location = obj.Location(driver, location_name.rstrip('\n'), save_dir)
                    try:
                        location.download_center_map()
                        location.calculate_coordinates()
                        location_objects.append(location)
                    finally:
                        if os.path.isfile(os.path.join(save_dir, 'boundaries.png')):
                            os.remove(os.path.join(save_dir, 'boundaries.png'))
            if not args.output_loc.endswith('.kml'):
                try:
                    os.makedirs(args.output_loc)
                except FileExistsError:
                    pass
    finally:
        if os.path.exists(save_dir):
            shutil.rmtree(save_dir)
        if not file_empty:
            utils.write_to_kml(location_objects, args.output_loc)
            driver.close()

if __name__ == '__main__':
    main()