#!/usr/bin/env 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
from nazoru.led import LED_BLUE, LED_RED
LED_RED.blink(1)

import argparse
import os
from nazoru import get_default_graph_path
from nazoru.core import create_keyboard_recorder, Bluetooth, NazoruPredictor

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)

  print('Ready. Please input your scrrible.')
  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_RED.on()
    result = predictor.predict_top_n(data, 5)
    LED_RED.off()

    print('\n=== RESULTS ===')
    for item in result:
      print(u'%s (%s): %.5f' % (item[0], item[1], item[2]))
    print('===============\n')

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

if __name__ == '__main__':
  main()
