import re


def get_flex_counters(module):
    """
    @summary: Parse output of "counterpoll show" command and convert it to the dictionary.
              Composed dictionary example:
              {'PG_WATERMARK_STAT': {'Interval': '10000', 'Status': 'enable'},
              'PORT_STAT': {'Interval': '10000', 'Status': 'enable'},
              'QUEUE_STAT': {'Interval': '10000', 'Status': 'enable'},
              'QUEUE_WATERMARK_STAT': {'Interval': '10000', 'Status': 'enable'}}

              CLI output example:
              Type                  Interval (in ms)    Status
              --------------------  ------------------  --------
              QUEUE_STAT            default (10000)     enable
              PORT_STAT             default (1000)      enable
              QUEUE_WATERMARK_STAT  default (10000)     enable
              PG_WATERMARK_STAT     default (10000)     enable
    @param module: The AnsibleModule object
    @return: Return dictionary of parsed counters
    """
    result = {}
    cli_cmd = "counterpoll show"
    skip_lines = 2

    rc, stdout, stderr = module.run_command(cli_cmd)
    if rc != 0:
        module.fail_json(msg="Failed to run {}, rc={}, stdout={}, stderr={}".format(cli_cmd, rc, stdout, stderr))

    try:
        for line in stdout.splitlines()[skip_lines:]:
            if line:
                key = line.split()[0]
                matched = re.search("{}.*(enable|disable)".format(key), line)
                if matched:
                    counter_line = matched.group(0).split()
                    result[key] = {}
                    # Output line will contain 4 columns if default was not changed
                    # And 3 columns if default was changed
                    index = 2 if len(counter_line) % 3 else 1
                    result[key]["Interval"] = counter_line[index].strip("(|)")
                    result[key]["Status"] = counter_line[-1]
    except Exception as e:
        module.fail_json(msg="Failed to parse output of '{}', err={}".format(cli_cmd, str(e)))

    return result