#!/usr/bin/env python
#
# Copyright 2009 Dan Smith <dsmith@danplanet.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import argparse
import logging
import sys
import serial

from chirp import chirp_common
from chirp.drivers import idrp


def open_device(dev):
    try:
        s = serial.Serial(port=dev,
                          baudrate=idrp.IDRPx000V.BAUD_RATE,
                          timeout=0.1)
    except Exception as e:
        print("Unable to open serial port %s: %s" % (dev, e))
        return None

    rp = idrp.IDRPx000V(s)

    return rp


def read_freq(dev):
    rp = open_device(dev)
    if not rp:
        return 0

    try:
        mem = rp.get_memory(0)
    except Exception as e:
        print("Unable to read memory from device: %s" % e)
        return 0

    rp.pipe.close()

    return mem.freq


def _set_freq(rp):
    try:
        mem = rp.get_memory(0)
    except Exception as e:
        print("Unable to read memory from device: %s" % e)
        return False

    print("\nNew frequency [%s]: " % chirp_common.format_freq(mem.freq))
    input = sys.stdin.readline().strip()

    if not input:
        print("Frequency unchanged")
        return False

    try:
        mem.freq = chirp_common.parse_freq(input)
    except Exception:
        print("Invalid entry `%s'" % input)
        return False

    try:
        rp.set_memory(mem)
    except Exception as e:
        print("Failed to set frequency to %s: %s" % (
                  chirp_common.format_freq(mem.freq), e))
        return False

    print("Successfully set frequency to %s" % (
              chirp_common.format_freq(mem.freq)))
    return True


def set_freq(dev):
    rp = open_device(dev)
    if not rp:
        return

    try:
        res = _set_freq(rp)
    except Exception as e:
        print("Unknown error while setting frequency: %s" % e)
        res = False

    rp.pipe.close()
    return res


def main_menu(dev):
    print("Looking for a repeater...")
    sys.stdout.flush()
    freq = read_freq(dev)
    if not freq:
        return 1
    print("\r                                          \r")

    cmd = ""
    while cmd != "3":
        print("""
KK7DS ID-RP* Frequency Tool
Current Setting: %s
--------------------------------
1. Set repeater frequency
2. Re-read current frequency
3. Quit
--------------------------------
> """ % chirp_common.format_freq(freq))

        cmd = sys.stdin.readline().strip()

        if cmd == "1":
            if set_freq(dev):
                freq = read_freq(dev)
        elif cmd == "2":
            freq = read_freq(dev)
        elif cmd != "3":
            print("Invalid entry")

    return 0


if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument('dev', help='Serial device')
    p.add_argument('--debug', action='store_true')
    args = p.parse_args()
    logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARNING)
    sys.exit(main_menu(args.dev))
