"""Make config files for the multi-camera app.

camera_ranges.json
camera_settings.json
button_mapping.json

Original author: Mark Zvilius, 20-July-2019
For: The Sexton Corp
"""
import os
import json

CONFIGDIR = 'config/'

def make_camera_ranges(config_dir):
    """All possible values for the various camera settings.
    Rarely if ever changes.
    """
    FILE_PATH = config_dir + 'camera_ranges.json'

    ranges = {}
    ranges['iso'] = ['500', '640', '800', '1000', '1250', '1600', '2000', 
                '2500', '3200', '4000', '5000', '6400', '8000', '10000',
                '12800', '16000', '20000', '25600', '32000', '40000',
                '51200', '64000', '80000', '102400']

    ranges['mwb'] = ['2500', '3000', '3500', '4000', '4500', '5000',
                '5500', '6000', '6500', '7000', '7500']

    ranges['shutter_time'] = ['1/30', '1/40', '1/48', '1/50', '1/60', '1/80',
                '1/100', '1/120', '1/125', '1/160', '1/200', '1/240', '1/250',
                '1/320', '1/400', '1/500', '1/640', '1/800', '1/1000', '1/1250',
                '1/1600', '1/2000', '1/2500', '1/3200', '1/4000', '1/5000',
                '1/6400', '1/8000']

    ranges['video_encoder'] = ['H.265', 'ProRes%20422%20LT', 'ProRes%20422']

    ranges['iris'] = ['2', '2.8', '4.5', '5.6', '8', '11']

    fp = open(FILE_PATH, 'w')
    json.dump(ranges, fp)
    print('created %s' % (FILE_PATH))


def make_default_settings(config_dir):
    """Camera settings that the user can change are persisted to this file."""

    FILE_PATH = config_dir + 'camera_settings.json'

    settings = {'iso':'800', 'mwb':'6500', 'shutter_time':'1/100',
                'video_encoder':'H.265', 'iris':'5.6', 'project_fps':'29.97'}

    fp = open(FILE_PATH, 'w')
    json.dump(settings, fp)
    print('created %s' % (FILE_PATH))


def make_button_map(config_dir):
    """Map pushbuttons on GPIO Extender to their functions.

    Locations on GPIO Extender are specified as A0-A7 and B0-B7.
    """
    FILE_PATH = config_dir + 'button_mapping.json'

    buttons = { 'A0':'shutter_dn',
                'A1':'shutter_up',
                'A2':'wb_dn',
                'A3':'wb_up',
                'A4':'cam_dn',
                'A5':'cam_up',
                'B0':'fstop',
                'B1':'encoder',
                'B2':'iso_dn',
                'B3':'iso_up',
                'B4':'record'
              }

    fp = open(FILE_PATH, 'w')
    json.dump(buttons, fp)
    print('created %s' % (FILE_PATH))


if __name__ == '__main__':
    try:
        os.mkdir(CONFIGDIR)
    except FileExistsError:
        pass

    make_camera_ranges(CONFIGDIR)
    make_default_settings(CONFIGDIR)
    make_button_map(CONFIGDIR)

