#!/usr/bin/python3
# Copyright (c) 2022-2022
# Bruno Grasland bgr_bgr@gmx.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 sys,argparse
import phonenumbers
import webbrowser
import tkinter
from tkinter import messagebox
parser = argparse.ArgumentParser()
parser.add_argument('phoneNumber', help="phone number: any format")
parser.add_argument('region',help="Region/country code (where you reside): 2 uppercase letters")
args = parser.parse_args()

raw_number = str(args.phoneNumber)
local_region = str(args.region)
top =  tkinter.Tk()
top.withdraw()
try:
  x = phonenumbers.parse(raw_number,local_region)
except:
  message="'{}'\n is not a valid phone number" .format(raw_number)
  print(message)
  messagebox.showerror("Error",message)
  exit()

if not phonenumbers.phonenumberutil.is_nanpa_country(phonenumbers.phonenumberutil.region_code_for_number(x)):
  message="{}\n{} is not part of NANPA".format(raw_number ,phonenumbers.phonenumberutil.region_code_for_number(x))
  print(message)
  messagebox.showerror("Error",message)
  exit()

newNumFormat =phonenumbers.NumberFormat(pattern="(\\d{3})(\\d{3})(\\d{4})", format="\\1-\\2-\\3")
newNumFormat._mutable = True
newNumberFormats = [newNumFormat]
hyphen_formated_number=phonenumbers.format_by_pattern(x, phonenumbers.PhoneNumberFormat.NATIONAL,newNumberFormats)
url="https://www.usphonebook.com/{}".format(hyphen_formated_number)
webbrowser.open_new(url)
exit()

