"""
GCode M
List all implemented M-codes (help)

Author: Elias Bakken
email: elias.bakken(at)gmail(dot)com
Website: http://www.thing-printer.com
License: CC BY-SA: http://creativecommons.org/licenses/by-sa/2.0/
"""
from __future__ import absolute_import

from .GCodeCommand import GCodeCommand


class M(GCodeCommand):
  def execute(self, g):
    gcodes = self.printer.processor.get_supported_commands_and_description()
    self.printer.send_message(g.prot, "Implemented M-codes:")
    if g.has_letter("F"):
      formatting = g.get_int_by_letter("F", 0)
      # Format for Wiki
      if formatting == 0:
        self.printer.send_message(g.prot, "===M: List of currently implemented M-codes===")
        self.printer.send_message(g.prot,
                                  "This list has been autogenerated by issuing 'M F0' in Redeem")
        for gcode, desc in sorted(gcodes.items()):
          if gcode[0] == "M":
            self.printer.send_message(g.prot, "====" + gcode + ": " + desc + "====")
            l_desc = self.printer.processor.gcodes[gcode].get_long_description().replace(
                "\n", "<br>\n")
            self.printer.send_message(g.prot, l_desc)

      else:
        self.printer.send_message(g.prot, "Wrong formatting")
    else:
      highlight = ""
      if g.has_letter("S"):
        highlight = g.get_int_by_letter("S")
        #print("Highlight: "+str(highlight))
      for gcode, desc in sorted(gcodes.items()):
        if gcode[0] == "M":
          ret = gcode + ": " + desc
          if highlight:
            if highlight in ret:
              self.printer.send_message(g.prot, ret)
          else:
            self.printer.send_message(g.prot, ret)

  def get_description(self):
    return "List all M-codes"

  def get_long_description(self):
    return ("Lists all the M-codes implemented by this firmware. "
            "To get a long description of each code use '?' "
            "after the code name, for instance, M92? will give a decription of M92. "
            "To get all g-codes with wiki formatting, add token 'F0'.\n"
            "To search for a phrase add S<phrase>")
