#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# System modules
from astropy.time import Time
import importlib
import json
import sys

# Custom modules
from utils.logger import log
# import templates

class Sequencer():
    def __init__(self):
        self.ob = []
        
    def load_file(self, ob_file):
        with open(ob_file) as jsonfile:
            log.info(f"Loading the ob from file {ob_file}")
            try:
                self.ob = json.load(jsonfile)
            except json.decoder.JSONDecodeError as e:
                log.error("Probably malformed json")
                log.error(e)
            except UnicodeDecodeError as e:
                log.error("Not a text file")
                log.error(e)                
            except Exception as e:
                log.error("Not handled exception")
                raise(e)

    
    def execute(self):
        ob = self.ob if type(self.ob) == list else [self.ob]

        log.info(f"There are {len(ob)} templates in the ob")

        now = Time.now()
        
        for template in ob:
            log.info("--------------------------------------------")
            try:
                
                # Importing the module given its name in the json.
                tplmodule = importlib.import_module("templates."+template["template"])
                # tplmodule = getattr(templates, template["template"])
                # Every template module has a Template() class.
                tpl = tplmodule.Template()
                # Run the template given its parameters in the json.
                tpl.run(template["params"])

            except AttributeError as e:
                log.error(e)

            except KeyError as e:
                log.error(f"{e} is not defined")

            except KeyboardInterrupt as e:
                log.error("Interrupt triggered")
                log.error(e)
                tpl.abort()
                self.abort()
                return
                
        log.debug(f"Total elapsed time: {(Time.now()-now).sec :.2f}s")
        
    def abort(self):
        log.error(f"Aborting sequencer")
        sys.exit(1)
        return

    
def main():
    import sys
    
    seq = Sequencer()
    seq.load_file(sys.argv[1])
    seq.execute()
    
if __name__ == "__main__":

    main()
