#!/usr/bin/env python3

"""
Copyright 2018-2019 Dover Microsystems, Inc.

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
import os

from resources import verdi_interface as verdi
from resources import view
from resources import model
from resources import config

class Controller():
    """Code that stitches the model and view classes together"""

    def __init__(self):

        # Determine the Verdi instance with which to interact.
        self.verdi = verdi.Interface()
        candidates = self.verdi.get_candidates_for_wave_tk_name()
        assert(len(candidates) > 0), 'No Verdi app candidates found.'

        # Create the main view now that a GUI is needed to continue.
        callback = self.view_callback_handler
        self.view = view.MainView(callback=callback,
                                  cleanup=self.cleanup)

        if len(candidates) == 1:
            # Only a single candidate so must be the correct one.
            self.candidate = candidates[0]
        else:
            # More than one candidate so use GUI to help user choose.
            prompt = 'Choose a Verdi instance:'
            title  = 'Wave Selection'
            self.candidate = self.view.chooser(title=title,
                                               prompt=prompt,
                                               candidates=candidates)

        if self.candidate is not None:
            self.verdi.set_wave_tk_name(self.candidate)

            # Now that the Verdi app is known...
            # ...register the callback for when the cursor changes.
            callback = self.verdi_callback_handler
            self.verdi.add_time_change_work(callback)
            self.verdi.register_time_change_callback()
            # ...and update the label name.
            self.view.update_wave_app(self.verdi.get_wave_tk_name())
            # ...and get the cursor value and display the time.
            time_at_cursor = self.verdi.get_time_at_cursor()
            self.view.update_cursor_time(time_at_cursor)

            wave_filename = self.verdi.get_wave_filename()
            (file_root, file_name) = os.path.split(wave_filename)

            if isinstance(config.listing, str):
                base_listings = [config.listing]
            else:
                base_listings = config.listing

            listings = [file_root + '/' + i for i in base_listings]
            self.model = model.CodeModel(listings=listings)

            labeled_code = self.model.get_labeled_code()
            self.view.apply_labeled_code(labeled_code)

            # Now that the code model and view have been created,
            # update the view to highlight the current instruction.
            self.recenter()

    def go(self):
        if self.candidate is not None:
            self.view.go()
        else:
            self.cleanup()

    def view_callback_handler(self, reason):
        legal_reasons = {'Prev', 'Next', 'Center'}
        assert(reason in legal_reasons), 'Unrecognized reason.'
        if reason == 'Center':
            self.recenter()
        else:
            self.verdi.search_signal_change(signal=config.ip_signal,
                                            direction=reason)

    def recenter(self):
        ip_value = self.verdi.get_sig_value_by_time(config.ip_signal)
        line = self.model.get_line_from_instr_ptr(ip_value)
        self.view.recenter(line)

    def verdi_callback_handler(self, time):
        self.view.update_cursor_time(time)
        self.recenter()

    def cleanup(self):
        self.verdi.cleanup()
        self.view.cleanup()

controller = Controller()

# Run the guts of the application.
controller.go()
