# Copyright 3D Control Systems, Inc. All Rights Reserved 2017-2019.
# Built in San Francisco.

# This software is distributed under a commercial license for personal,
# educational, corporate or any other use.
# The software as a whole or any parts of it is prohibited for distribution or
# use without obtaining a license from 3D Control Systems, Inc.

# All software licenses are subject to the 3DPrinterOS terms of use
# (available at https://www.3dprinteros.com/terms-and-conditions/),
# and privacy policy (available at https://www.3dprinteros.com/privacy-policy/)

import re

import threaded_sender
from blocking_heating_emulator import BlockingHeatingEmulator


class Sender(threaded_sender.Sender):

    TEMPERATURE_ACKS_PREFIXES = [b"T:", b"B:"]

    def __init__(self, parent, usb_info, profile):
        threaded_sender.Sender.__init__(self, parent, usb_info, profile)
        self.heating_emulator = BlockingHeatingEmulator(self)

    def define_regexps(self):
        threaded_sender.Sender.define_regexps(self)
        self.temp_re = re.compile(rb'.*ok T:([\d\.]+) /([\d\.]+) .* B:(-?[\d\.]+) /(-?[\d\.]+) .*')
        self.wait_tool_temp_re = re.compile(rb'T:([\d\.]+) /([\d\.]+) @')
        self.wait_platform_temp_re = re.compile(rb'B:([\d\.]+) /([\d\.]+) @')

    def _parse_waiting_temperature_updates(self, line):
        match = self.wait_tool_temp_re.match(line)
        if match:
            self.temps[1] = float(match.group(1))
            self.target_temps[1] = float(match.group(2))
            self.heating = True

    def parse_waiting_platform_temperature_updates(self, line):
        match = self.wait_platform_temp_re.match(line)
        if match:
            self.temps[0] = float(match.group(1))
            self.target_temps[0] = float(match.group(2))
            self.heating = True

    def _log_strange_acks(self, line):
        if line[0] == b"B" or (len(line) > 1 and line[1] == b"B"):
            self.parse_waiting_platform_temperature_updates(line)
            self.operational_flag = True
        else:
            self.logger.warning("Received: %s" % line.strip())

