#!/usr/bin/python3

import argparse
import os

import filer

desc = 'change string in files'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('-v', action='store_true', help='raise verbosity')
parser.add_argument('old', metavar='old', type=str, help='old string')
parser.add_argument('new', metavar='new', type=str, help='new string')
parser.add_argument('files', metavar='files', type=str, nargs='+',
                    help='files')
args = parser.parse_args()

has_blank = False
if ' ' in args.old:
    has_blank = True
    old_nobsp = args.old.replace(' ', ' ')
    new_nobsp = args.new.replace(' ', ' ')
print(old_nobsp)

files = args.files
for the_file in files:
    check_nobsp = False
    if has_blank and the_file.endswith('.html'):
        if args.v:
            print("I also do the non-breaking space.")
        check_nobsp = True
    if not os.path.isfile(the_file):
        continue
    if args.v:
        print(f"I read {the_file}")
    txt = filer.sread(the_file)
    if args.old not in txt:
        if check_nobsp and old_nobsp not in txt:
            if args.v:
                print(f"{args.old} is not in {the_file}")
            continue
        else:
            if args.v:
                print(f"{args.old} is not in {the_file}")
            continue
    txt = txt.replace(args.old, args.new)
    if check_nobsp:
        txt = txt.replace(old_nobsp, new_nobsp)
    filer.srite(the_file, txt, do_change_check=False,
                do_preserve_time=True)
    if args.v:
        print(f"I changed {the_file}")
