#!/usr/bin/python3

import os
import argparse
import sys
import datetime
import json
import shelve

from geopy.geocoders import Nominatim

import lib.gmail
import lib.GEO
import lib.NY
import lib.NJ


class VaccineFinder:
    def __init__(self, config_fname):
        self.config = json.load(open(config_fname, 'r'))

        os.makedirs(self.config['data_dir'], exist_ok=True)
        self.data_dir = self.config['data_dir']
        os.makedirs(os.path.dirname(self.config['geodb']), exist_ok=True)
        self.position_db = shelve.open(self.config['geodb'])

    def save_data(self, name, data):
        now = datetime.datetime.now()
        out = self.data_dir + '/' + now.strftime('%Y%m%d.%H%M%S') + '.%s.json' % name
        fh = open(out, 'w')
        json.dump(data, fh)
        fh.close()

    def get_data(self, module):
        data = module.get_json()
        self.save_data(module.__name__, data)
        data = module.available_only(data)

        valid_sites = []
        for res in data:
            address = module.extract_addres(res)

            if address not in self.position_db:
                geolocator = Nominatim(user_agent="vaccine-finder")
                location = geolocator.geocode(address)
                if not location:
                    continue

                self.position_db[address] = lib.GEO.lat_lon_distance_km(self.config['home'], location.point)

            distance = self.position_db[address]
            if distance < self.config['distance_km_threshold']:
                valid_sites.append(res)

        return valid_sites

    def run(self):
        msg = ''
        for module in [lib.NY, lib.NJ]:
            res = self.get_data(module)
            if res:
                msg += '<p></p>'
                msg += lib.gmail.render_html_table(module.__name__, res)

        if msg:
            lib.gmail.send_mail(self.config['from_email'], self.config['email_password'], self.config['to_email'], 'vaccine sites', msg) 


def run(args):
    vf = VaccineFinder(args.config)
    vf.run()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='check websites for vaccines')
    parser.add_argument('-c', '--config', required=True, help='configuration file')
    args = parser.parse_args()
    run(args)

    sys.exit(0)
