#!python
# -*- coding: utf-8 -*-
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function

# Surpress warnings. Please unvail these warnings when development.
import warnings
warnings.filterwarnings("ignore", category=RuntimeWarning)
warnings.filterwarnings("ignore", category=FutureWarning)

from nazoru.led import LED_BLUE, LED_RED, LED_CHASSIS
import time
LED_RED.blink(1)
LED_CHASSIS.on()
time.sleep(1)
LED_CHASSIS.off()

import argparse
import os
import unicodedata
from nazoru import get_default_graph_path
from nazoru.core import (
    create_keyboard_recorder, Bluetooth, NazoruPredictor, clear_screen)

def main():
  FLAGS = None
  parser = argparse.ArgumentParser()
  parser.add_argument('-g', '--graph',
                      type=str,
                      default=get_default_graph_path(),
                      help='Path to a trained model which is generated by ' +
                           'nazoru-training.')
  parser.add_argument('-v', '--verbose', action='store_true')
  FLAGS, unparsed = parser.parse_known_args()

  LED_RED.blink(0.3)

  bt_connection = Bluetooth()
  try:
    recorder = create_keyboard_recorder(verbose=FLAGS.verbose)
  except IOError as e:
    LED_RED.off()
    LED_BLUE.off()
    raise e
  predictor = NazoruPredictor(FLAGS.graph)

  LED_RED.off()
  LED_BLUE.blink(1)
  LED_CHASSIS.set_brightness(5)

  print('Ready. Please scrrible on your keyboard.')
  while True:
    data, command = recorder.record()
    if command is not None:
      print('command: %s' % command)
      bt_connection.command(command)
      continue
    if data is None:
      print('done.')
      break

    LED_CHASSIS.set_brightness(100)
    LED_RED.on()
    try:
      result = predictor.predict_top_n(data, 5)
    except IndexError:
      # This is possible when pressing keys we don't use for learning.
      print('Invalid input. (out of range)')
      continue
    except ValueError:
      # This is possible when pressing only one key.
      print('Invalid input. (one key)')
      continue
    LED_RED.off()
    LED_CHASSIS.set_brightness(5)

    clear_screen()
    print('\n===== RESULTS =====')
    for item in result:
      if unicodedata.east_asian_width(item[0]) in {'W', 'F'}:
        surface = item[0]
      else:
        surface = item[0] + ' '
      print(u'%s (%4s): %.5f' % (surface, item[1], item[2]))
    print('===================\n')

    most_likely_result = result[0]
    print(u'prediction: %s (%s)' % (
      most_likely_result[0], most_likely_result[1]))
    bt_connection.send(most_likely_result[1])

if __name__ == '__main__':
  main()
