# Path: sheetsite/chain.py
# def apply_chain(site, path):
# 
#     if not(os.path.exists(path)):
#         os.makedirs(path)
# 
#     source = site['source']
#     destination = site['destination']
#     tweaks = site.get('tweaks')
# 
#     wb = None
# 
#     raw_file = os.path.join(path, 'raw.json')
#     if 'cache' in source:
#         wb = read_source({
#             'filename': raw_file
#         })
#     else:
#         wb = read_source(source)
# 
#     ss = Site(wb, os.path.join(path, 'geocache.sqlite'))
#     if 'flags' in site:
#         ss.configure(site['flags'])
#     output_file = os.path.join(path, 'public.json')
#     prev_raw_file = os.path.join(path, 'prev_raw.json')
#     private_output_file = os.path.join(path, 'private.json')
#     id_file = os.path.join(path, 'ids.json')
#     prev_id_file = os.path.join(path, 'prev_ids.json')
#     if os.path.exists(raw_file):
#         shutil.copyfile(raw_file, prev_raw_file)
#         if os.path.exists(id_file):
#             shutil.copyfile(id_file, prev_id_file)
# 
#     ss.save_local(raw_file, enhance=False)
# 
#     ids = process_ids(prev_raw_file, raw_file, prev_id_file, id_file)
#     ss.add_ids(ids)
# 
#     state = {
#         'path': path,
#         'output_file': output_file,
#         'id_file': id_file
#     }
# 
#     if tweaks:
#         import json
#         wj = json.load(open(raw_file, 'r'))
#         if hasattr(tweaks, 'items'):
#             tweak_items = tweaks.items()
#         else:
#             tweak_items = [[params['tweak'], params] for params in tweaks]
#         for tweak, params in tweak_items:
#             print("Working on tweak", json.dumps(tweak))
#             if 'tweak' in params:
#                 tweak = params['tweak']
#             import importlib
#             mod = importlib.import_module('sheetsite.tweaks.{}'.format(tweak))
#             ct = 2
#             try:
#                 target = mod.apply3
#                 ct = 3
#             except AttributeError:
#                 target = mod.apply
#             if ct == 3:
#                 target(Sheets(wj), params, state)
#             else:
#                 target(Sheets(wj), params)
#         from sheetsite.json_spreadsheet import JsonSpreadsheet
#         ss.workbook = JsonSpreadsheet(None, data=wj)
# 
#     ss.save_local(output_file)
#     if not os.path.exists(prev_raw_file):
#         # once daff can cope with blank tables correctly, switch to this
#         # with open(prev_raw_file, 'w') as fout:
#         #    fout.write('{ "names": [], "tables": [] }')
#         shutil.copyfile(raw_file, prev_raw_file)
#         shutil.copyfile(id_file, prev_id_file)
#     ss.save_local(private_output_file, private_sheets=True)
# 
#     state['workbook'] = ss.public_workbook()
# 
#     write_destination(destination, state)
# 
#     return {
#         'prev_raw_file': prev_raw_file,
#         'raw_file': raw_file
#     }
# 
# Path: sheetsite/cmdline.py
# def run(argv):
#     parser = argparse.ArgumentParser(description='Run a website from a spreadsheet. '
#                                      'Take a spreadsheet (from google sheets or locally), and '
#                                      'convert it to a .json file that a static website '
#                                      'generator like jekyll can use.  Optionally strip private '
#                                      'information and add derived geographic fields like '
#                                      'latitude and longitude.')
# 
#     parser.add_argument('--config', nargs='*', required=False,
#                         default=['_sheetsite.yml', '_sheetsite.json'],
#                         help='name of configuration file.')
# 
#     parser.add_argument('--cache-dir', nargs=1, required=False, default=['_cache'],
#                         help='name of default cache directory.')
# 
#     args = parser.parse_args(argv)
# 
#     config_file = None
#     for config_candidate in args.config:
#         if os.path.exists(config_candidate):
#             config_file = config_candidate
#             break
#     if not config_file:
#         print("Could not find config file", args.config)
#         exit(1)
#     params = load_config(config_file)
#     files = apply_chain(params, args.cache_dir[0])
#     diff = compute_diff(files, 'ansi')
#     print(diff)


import json
import os
import unittest
import contextlib
import shutil
import tempfile
from sheetsite.chain import apply_chain
from sheetsite.cmdline import run
                    "group": "web",
                    "address": {"places": ["street", "city", "state", "country"]},
                    "add": {"places": ["lat", "lon", "address"]}
                },
                "destination": {"output_file": target}
            }
            apply_chain(params, temp_dir)
            with open(target, 'r') as f:
                data = json.load(f)
            places = data["tables"]["places"]["rows"]
            self.assertEqual(places[0]["address"], "Test1 Test2")
            self.assertEqual(places[1]["address"], "Test1")
            self.assertEqual(places[2]["address"],
                             "305 Memorial Dr Cambridge Massachusetts United States")
            self.assertEqual(places[3]["address"],
                             "306 Memorial Dr Cambridge Massachusetts United States")

    def test_rename(self):
        with TemporaryDirectory() as temp_dir:
            target = "{}/out.json".format(temp_dir)
            params = {
                "source": {"filename": "tests/configs/multirow.json"},
                "flags": {
                    "geocoder": "dummy",
                    "rename": {"places": {"web": "website"}},
                    "address": {"places": ["street", "city", "state", "country"]},
                    "add": {"places": ["lat", "lon", "address"]}
                },
                "destination": {"output_file": target}
            }

# Path: sheetsite/chain.py
# def apply_chain(site, path):
# 
#     if not(os.path.exists(path)):
#         os.makedirs(path)
# 
#     source = site['source']
#     destination = site['destination']
#     tweaks = site.get('tweaks')
# 
#     wb = None
# 
#     raw_file = os.path.join(path, 'raw.json')
#     if 'cache' in source:
#         wb = read_source({
#             'filename': raw_file
#         })
#     else:
#         wb = read_source(source)
# 
#     ss = Site(wb, os.path.join(path, 'geocache.sqlite'))
#     if 'flags' in site:
#         ss.configure(site['flags'])
#     output_file = os.path.join(path, 'public.json')
#     prev_raw_file = os.path.join(path, 'prev_raw.json')
#     private_output_file = os.path.join(path, 'private.json')
#     id_file = os.path.join(path, 'ids.json')
#     prev_id_file = os.path.join(path, 'prev_ids.json')
#     if os.path.exists(raw_file):
#         shutil.copyfile(raw_file, prev_raw_file)
#         if os.path.exists(id_file):
#             shutil.copyfile(id_file, prev_id_file)
# 
#     ss.save_local(raw_file, enhance=False)
# 
#     ids = process_ids(prev_raw_file, raw_file, prev_id_file, id_file)
#     ss.add_ids(ids)
# 
#     state = {
#         'path': path,
#         'output_file': output_file,
#         'id_file': id_file
#     }
# 
#     if tweaks:
#         import json
#         wj = json.load(open(raw_file, 'r'))
#         if hasattr(tweaks, 'items'):
#             tweak_items = tweaks.items()
#         else:
#             tweak_items = [[params['tweak'], params] for params in tweaks]
#         for tweak, params in tweak_items:
#             print("Working on tweak", json.dumps(tweak))
#             if 'tweak' in params:
#                 tweak = params['tweak']
#             import importlib
#             mod = importlib.import_module('sheetsite.tweaks.{}'.format(tweak))
#             ct = 2
#             try:
#                 target = mod.apply3
#                 ct = 3
#             except AttributeError:
#                 target = mod.apply
#             if ct == 3:
#                 target(Sheets(wj), params, state)
#             else:
#                 target(Sheets(wj), params)
#         from sheetsite.json_spreadsheet import JsonSpreadsheet
#         ss.workbook = JsonSpreadsheet(None, data=wj)
# 
#     ss.save_local(output_file)
#     if not os.path.exists(prev_raw_file):
#         # once daff can cope with blank tables correctly, switch to this
#         # with open(prev_raw_file, 'w') as fout:
#         #    fout.write('{ "names": [], "tables": [] }')
#         shutil.copyfile(raw_file, prev_raw_file)
#         shutil.copyfile(id_file, prev_id_file)
#     ss.save_local(private_output_file, private_sheets=True)
# 
#     state['workbook'] = ss.public_workbook()
# 
#     write_destination(destination, state)
# 
#     return {
#         'prev_raw_file': prev_raw_file,
#         'raw_file': raw_file
#     }
# 
# Path: sheetsite/cmdline.py
# def run(argv):
#     parser = argparse.ArgumentParser(description='Run a website from a spreadsheet. '
#                                      'Take a spreadsheet (from google sheets or locally), and '
#                                      'convert it to a .json file that a static website '
#                                      'generator like jekyll can use.  Optionally strip private '
#                                      'information and add derived geographic fields like '
#                                      'latitude and longitude.')
# 
#     parser.add_argument('--config', nargs='*', required=False,
#                         default=['_sheetsite.yml', '_sheetsite.json'],
#                         help='name of configuration file.')
# 
#     parser.add_argument('--cache-dir', nargs=1, required=False, default=['_cache'],
#                         help='name of default cache directory.')
# 
#     args = parser.parse_args(argv)
# 
#     config_file = None
#     for config_candidate in args.config:
#         if os.path.exists(config_candidate):
#             config_file = config_candidate
#             break
#     if not config_file:
#         print("Could not find config file", args.config)
#         exit(1)
#     params = load_config(config_file)
#     files = apply_chain(params, args.cache_dir[0])
#     diff = compute_diff(files, 'ansi')
#     print(diff)


# Path: tests/test_chain.py
import json
import os
import unittest
import contextlib
import shutil
import tempfile
from sheetsite.chain import apply_chain
from sheetsite.cmdline import run

                    "group": "web",
                    "address": {"places": ["street", "city", "state", "country"]},
                    "add": {"places": ["lat", "lon", "address"]}
                },
                "destination": {"output_file": target}
            }
            apply_chain(params, temp_dir)
            with open(target, 'r') as f:
                data = json.load(f)
            places = data["tables"]["places"]["rows"]
            self.assertEqual(places[0]["address"], "Test1 Test2")
            self.assertEqual(places[1]["address"], "Test1")
            self.assertEqual(places[2]["address"],
                             "305 Memorial Dr Cambridge Massachusetts United States")
            self.assertEqual(places[3]["address"],
                             "306 Memorial Dr Cambridge Massachusetts United States")

    def test_rename(self):
        with TemporaryDirectory() as temp_dir:
            target = "{}/out.json".format(temp_dir)
            params = {
                "source": {"filename": "tests/configs/multirow.json"},
                "flags": {
                    "geocoder": "dummy",
                    "rename": {"places": {"web": "website"}},
                    "address": {"places": ["street", "city", "state", "country"]},
                    "add": {"places": ["lat", "lon", "address"]}
                },
                "destination": {"output_file": target}
            }

            apply_chain(params, temp_dir)