"""submonitor.py

The submission monitor polls to identify and fetch newly available images.
"""

import os, logging, json, subprocess


from .scottylabs import Submissions

#================================================================
class SubmissionMonitor(object):
    def __init__(self, config, gdrive):
        logging.debug("Entering SubmissionMonitor.__init__ and initializing superclasses")
        super(SubmissionMonitor, self).__init__()

        self.archive_path    = "B-archived-submissions"
        self.new_file_path   = "1-new-submissions"

        self.ready = True

        if not os.path.isdir(self.archive_path):
            logging.error("Archive folder not found: %s", self.archive_path)
            self.ready = False

        if not os.path.isdir(self.new_file_path):
            logging.error("New file folder not found: %s", self.new_file_path)
            self.ready = False

        self.backend = Submissions(config)
        self.gdrive = gdrive
        
        return
    
    def get_submission_ids(self):
        data = self.backend.fetch_submission_metadata()
        if data is not None:
            with open('submissions.json', 'w') as file:
                file.write(json.dumps(data, indent=2))
            ids = self.backend.get_all_image_ids(data)
            return data, ids
        else:
            return None

    def get_archived_ids(self):
        archived = os.listdir(self.archive_path)
        return [os.path.splitext(name)[0] for name in archived]

    def find_new_ids(self, submitted, cached):
        return 

    def fetch_new_submission(self, record, img_id):
        readable_name = self.backend.make_filename(record)

        data = self.gdrive.download_submitted_image(img_id)
        
        if data is None:
            # assume it no longer exists on GDrive and just make a placeholder
            filepath = os.path.join(self.archive_path, img_id + '.txt')
            with open(filepath, 'w') as file:
                file.write('%s missing\n' % (readable_name))

        else:
            filepath = os.path.join(self.archive_path, img_id + '.png')
            with open(filepath, 'wb') as file:
                file.write(data)
            logging.info("Saved new submission %s", filepath)

            # make a second copy in the human-readable input folder
            readable_path = os.path.join(self.new_file_path, readable_name)            
            logging.info("Copying to %s", readable_path)
            subprocess.run(['cp', filepath, readable_path])
    
    def poll(self):
        logging.info("SubmissionMonitor starting scan...")

        metadata, submitted_ids = self.get_submission_ids()
        archived  = self.get_archived_ids()
        new_ids   = set(submitted_ids).difference(set(archived))

        if len(new_ids) > 0:
            logging.debug("SubmissionMonitor found new submissions: %s", new_ids)
            for img_id in new_ids:
                record = self.backend.find_record(metadata, img_id)
                self.fetch_new_submission(record, img_id)
