# Copyright 2016:
# * Jim Unroe KC9HI, <rock.unroe@gmail.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 2 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 time
import struct
import logging
import re

LOG = logging.getLogger(__name__)

from chirp.drivers import baofeng_common
from chirp import chirp_common, directory, memmap
from chirp import bitwise, errors, util
from chirp.settings import RadioSettingGroup, RadioSetting, \
    RadioSettingValueBoolean, RadioSettingValueList, \
    RadioSettingValueString, RadioSettingValueInteger, \
    RadioSettingValueFloat, RadioSettings, \
    InvalidValueError
from textwrap import dedent

##### MAGICS #########################################################

# BTECH GMRS-V1 magic string
MSTRING_GMRSV1 = "\x50\x5F\x20\x15\x12\x15\x4D"

##### ID strings #####################################################

# BTECH GMRS-V1
GMRSV1_fp1 = "US32411"

DTMF_CHARS = "0123456789 *#ABCD"
STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 20.0, 25.0, 50.0]

LIST_AB = ["A", "B"]
LIST_ALMOD = ["Off", "Site", "Tone", "Code"]
LIST_BANDWIDTH = ["Wide", "Narrow"]
LIST_COLOR = ["Off", "Blue", "Orange", "Purple"]
LIST_DTMFSPEED = ["%s ms" % x for x in range(50, 2010, 10)]
LIST_DTMFST = ["Off", "DT-ST", "ANI-ST", "DT+ANI"]
LIST_MODE = ["Channel", "Name", "Frequency"]
LIST_OFF1TO9 = ["Off"] + list("123456789")
LIST_OFF1TO10 = LIST_OFF1TO9 + ["10"]
LIST_OFFAB = ["Off"] + LIST_AB
LIST_RESUME = ["TO", "CO", "SE"]
LIST_PONMSG = ["Full", "Message"]
LIST_PTTID = ["Off", "BOT", "EOT", "Both"]
LIST_SCODE = ["%s" % x for x in range(1, 16)]
LIST_RPSTE = ["Off"] + ["%s" % x for x in range(1, 11)]
LIST_RTONE = ["1000 Hz", "1450 Hz", "1750 Hz", "2100 Hz"]
LIST_SAVE = ["Off", "1:1", "1:2", "1:3", "1:4"]
LIST_SHIFTD = ["Off", "+", "-"]
LIST_STEDELAY = ["Off"] + ["%s ms" % x for x in range(100, 1100, 100)]
LIST_STEP = [str(x) for x in STEPS]
LIST_TIMEOUT = ["%s sec" % x for x in range(15, 615, 15)]
LIST_TXPOWER = ["High", "Low"]
LIST_VOICE = ["Off", "English", "Chinese"]
LIST_WORKMODE = ["Frequency", "Channel"]

def model_match(cls, data):
    """Match the opened/downloaded image to the correct version"""
    rid = data[0x1EF0:0x1EF7]

    if rid in cls._fileid:
        return True

    return False


class MyRadioFeatures(chirp_common.RadioFeatures):
    def validate_memory(self, mem):
        # Run the normal validation
        msgs = chirp_common.RadioFeatures.validate_memory(self, mem)

        # Run my validation
        if mem.number <= 6 and mem.mode != "NFM":
            msgs.append(chirp_common.ValidationError(
                        'Only NFM is supported on this channel'))

        return msgs


@directory.register
class GMRSV1(baofeng_common.BaofengCommonHT):
    """BTech GMRS-V1"""
    VENDOR = "BTECH"
    MODEL = "GMRS-V1"

    _fileid = [GMRSV1_fp1, ]

    _magic = [MSTRING_GMRSV1, ]
    _magic_response_length = 8
    _fw_ver_start = 0x1EF0
    _recv_block_size = 0x40
    _mem_size = 0x2000
    _ack_block = True

    _ranges = [(0x0000, 0x0DF0),
               (0x0E00, 0x1800),
               (0x1EE0, 0x1EF0),
               (0x1F60, 0x1F70),
               (0x1F80, 0x1F90),
               (0x1FC0, 0x1FD0)]
    _send_block_size = 0x10

    MODES = ["NFM", "FM"]
    VALID_CHARS = chirp_common.CHARSET_ALPHANUMERIC + \
        "!@#$%^&*()+-=[]:\";'<>?,./"
    LENGTH_NAME = 7
    SKIP_VALUES = ["", "S"]
    DTCS_CODES = sorted(chirp_common.DTCS_CODES + [645])
    POWER_LEVELS = [chirp_common.PowerLevel("High", watts=5.00),
                    chirp_common.PowerLevel("Low", watts=2.00)]
    VALID_BANDS = [(130000000, 180000000),
                   (400000000, 521000000)]
    PTTID_LIST = LIST_PTTID
    SCODE_LIST = LIST_SCODE


    def get_features(self):
        """Get the radio's features"""

        rf = MyRadioFeatures()
        rf.has_settings = True
        rf.has_bank = False
        rf.has_tuning_step = False
        rf.can_odd_split = False
        rf.has_name = True
        rf.has_offset = False
        rf.has_mode = True
        rf.has_dtcs = True
        rf.has_rx_dtcs = True
        rf.has_dtcs_polarity = True
        rf.has_ctone = True
        rf.has_cross = True
        rf.valid_modes = self.MODES
        rf.valid_characters = self.VALID_CHARS
        rf.valid_name_length = self.LENGTH_NAME
        rf.valid_duplexes = []
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
        rf.valid_cross_modes = [
            "Tone->Tone",
            "DTCS->",
            "->DTCS",
            "Tone->DTCS",
            "DTCS->Tone",
            "->Tone",
            "DTCS->DTCS"]
        rf.valid_skips = self.SKIP_VALUES
        rf.valid_dtcs_codes = self.DTCS_CODES
        rf.memory_bounds = (0, 127)
        rf.valid_power_levels = self.POWER_LEVELS
        rf.valid_bands = self.VALID_BANDS

        return rf


    MEM_FORMAT = """
    #seekto 0x0000;
    struct {
      lbcd rxfreq[4];
      lbcd txfreq[4];
      ul16 rxtone;
      ul16 txtone;
      u8 unknown0:4,
         scode:4;
      u8 unknown1;
      u8 unknown2:7,
         lowpower:1;
      u8 unknown3:1,
         wide:1,
         unknown4:2,
         bcl:1,
         scan:1,
         pttid:2;
    } memory[128];

    #seekto 0x0B00;
    struct {
      u8 code[5];
      u8 unused[11];
    } pttid[15];
    
    #seekto 0x0CAA;
    struct {
      u8 code[5];      
      u8 unused1:6,    
         aniid:2;      
      u8 unknown[2];   
      u8 dtmfon;       
      u8 dtmfoff;      
    } ani;             
                       
    #seekto 0x0E20;    
    struct {           
      u8 unused01:4,   
         squelch:4;    
      u8 unused02;     
      u8 unused03;     
      u8 unused04:5,   
         save:3;       
      u8 unused05:4,   
         vox:4;        
      u8 unused06;     
      u8 unused07:4,   
         abr:4;        
      u8 unused08:7,   
         tdr:1;        
      u8 unused09:7,   
         beep:1;       
      u8 unused10:2,   
         timeout:6;    
      u8 unused11[4];  
      u8 unused12:6,   
         voice:2;      
      u8 unused13;     
      u8 unused14:6,   
         dtmfst:2;     
      u8 unused15;     
      u8 unused16:6,   
         screv:2;      
      u8
 unused17:6,   
         pttid:2;   
   
      u8 unused18:2,   
         pttlt:6;      
      u8 unused19:6,   
         mdfa:2;       
      u8 unused20:6,   
         mdfb:2;       
      u8 unused21;     
      u8 unused22:7,   
         sync:1;       
      u8 unused23[4];  
      u8 unused24:6,   
         wtled:2;      
      u8 unused25:6,   
         rxled:2;      
      u8 unused26:6,   
         txled:2;      
      u8 unused27:6,   
         almod:2;      
      u8 unused28:7,   
         dbptt:1;      
      u8 unused29:6,   
         tdrab:2;      
      u8 unused30:7,   
         ste:1;        
      u8 unused31:4,   
         rpste:4;      
      u8 unused32:4,   
         rptrl:4;      
      u8 unused33:7,   
         ponmsg:1;     
      u8 unused34:7,   
         roger:1;      
      u8 unused35:6,   
         rtone:2;      
      u8 unused36;     
      u8 unused37:6,   
         rogerrx:2;    
      u8 unused38;     
      u8 displayab:1,  
         unknown1:2,   
         fmradio:1,    
         alarm:1,      
         unknown2:1,   
         reset:1,      
         menu:1;       
      u8 unused39;     
      u8 workmode;     
      u8 keylock;      
      u8 cht;          
    } settings;        
                       
    #seekto 0x0E76;    
    struct {           
      u8 unused1:1,    
         mrcha:7;      
      u8 unused2:1,    
         mrchb:7;      
    } wmchannel;       
           