#!/usr/bin/env python3
# -*- mode: python -*-

"""
Simple script for helping rename TV shows
"""

# TODO: Need support for custom in/out
# TODO: Need support for callable rename objects

# TODO:  Use regex to get a list of all words in filename
#        then make sure only ours exist in it
#        If needed, use spellchecker or such to make sure extra words are valid

# TODO:  Need way to specify alternatives for words, like USA or U.S.A. or the like.
#        May be easiest to just allow refex for match, like its done for extraction.

# TODO:  To fix duplicate names with appended extras (CSI, CSI Miami, CSI New York, etc)
# Search through all the regexs keeping all the match results.  Whichever match result
# has the most words assoicated with it is the correct one.  If there is more than one
# of them with the same number of words and matches, print error and continue.

# TODO:  A new idea just occurred to me ... If I made a dictionary or regex that contained
# all the known words (all word: lists), then I could use it as a sort of sanity check in
# which to make sure that a show is really the show if it matches it's words: and didn't
# contain any of the rest of them ...

# TODO:  Cannot search for a word twice (e.g. Brooklyn Nine Nine).

# TODO:  Investigate '\w+' as re.findall() as it may be better/faster/etc.

import glob, sys, os
import re
from pprint import pprint
from vidis.models import db, FeedModel, RegexModel

DATEFMT = '{year:04d}-{month:02d}-{day:02d}'
DATES = [
# [yy]yy_mm_dd
    '(?P<year>(?:19|20)[0-9]{2})[- /.](?P<month>(?:0[1-9]|1[012]))[- /.](?P<day>(?:0[1-9]|[12][0-9]|3[01]))',    
# dd_mm_[yy]yy
    '(?P<day>(?:0[1-9]|[12][0-9]|3[01]))[- /.](?P<month>(?:0[1-9]|1[012]))[- /.](?P<year>(?:19|20)[0-9]{2})',
# mm_dd_[yy]yy
    '(?P<month>(?:0[1-9]|1[012]))[- /.](?P<day>(?:0[1-9]|[12][0-9]|3[01]))[- /.](?P<year>(?:19|20)[0-9]{2})'
]

# New (easier) way to add to RenameList
SimpleRenameList = {
    'The Odd Couple':                           {},
    'Eye Candy':                                {},
    'Wolf Hall':                                {},
    'X Company':                                {},
    'Hindsight':                                {},
    'Girlfriends Guide To Divorce':             {},
    'Catastrophe':                              { 'words': [ 'catastrophe' ] },
    'Chasing Life':                             { 'words': [ 'chasing', 'life' ] },
    'Better Call Saul':                         { 'words': [ 'better', 'call', 'saul' ] },
    'Allegiance':                               { 'words': [ 'allegiance' ] },
    'Fresh Off The Boat':                       { 'words': [ 'fresh', 'off', 'the', 'boat' ] },
    'Schitts Creek':                            { 'words': [ 'schitts', 'creek' ] },
    'Cockroaches':                              { 'words': [ 'cockroaches' ] },
    'Backstrom':                                { 'words': [ 'backstrom' ] },
    '12 Monkeys':                               { 'words': [ '12', 'monkeys' ] },
    'Man Seeking Woman':                        { 'words': [ 'man', 'seeking', 'woman' ] },
    'State Of Affairs':                         { 'words': [ 'state', 'of', 'affairs' ] },
    'Galavant':                                 { 'words': [ 'galavant' ] },
    'Spy World':                                { 'words': [ 'spy', 'world' ] },
    'Togetherness':                             { 'words': [ 'togetherness' ] },
    '1600 Penn':                                { 'words': [ '1600', 'penn' ] },
    '18 To Life':                               { 'words': [ '18', 'to', 'life' ] },
    '2 Broke Girls':                            { 'words': [ '2', 'broke', 'girls' ] },
    '24':                                       { 'last': True, 'words': [ '24' ] },
    '30 Rock':                                  { 'words': [ '30', 'rock' ] },
    '666 Park Avenue':                          { 'words': [ '666', 'park', 'avenue' ] },
    '90210':                                    { 'words': [ '90210' ] },
    'A Gifted Man':                             { 'words': [ 'a', 'gifted', 'man' ] },
    'A To Z':                                   { 'words': [ 'a', 'to', 'z' ] },
    'About A Boy':                              { 'words': [ 'about', 'a', 'boy' ] },
    'Accidentally On Purpose':                  { 'words': [ 'accidentally', 'on', 'purpose' ] },
    'Against The Wall':                         { 'words': [ 'against', 'the', 'wall' ] },
    'Alaska State Troopers':                    { 'words': [ 'alaska', 'state', 'troopers' ] },
    'Alcatraz':                                 { 'words': [ 'alcatraz' ] },
    'All About Aubrey':                         { 'words': [ 'all', 'about', 'aubrey' ] },
    'All Worked Up':                            { 'words': [ 'all', 'worked', 'up' ] },
    'Almost Human':                             { 'words': [ 'almost', 'human' ] },
    'Almost Royal':                             { 'words': [ 'almost', 'royal' ] },
    'Alphas':                                   { 'words': [ 'alphas' ] },
    'American Dad':                             { 'words': [ 'american', 'dad' ] },
    'American Horror Story':                    { 'words': [ 'american', 'horror', 'story' ] },
    'American Idol':                            { 'words': [ 'american', 'idol' ] },
    'American Restoration':                     { 'words': [ 'american', 'restoration' ] },
    'Animal Practice':                          { 'words': [ 'animal', 'practice' ] },
    'Archer':                                   { 'words': [ 'archer' ] },
    'Are You There Chelsea':                    { 'words': [ 'are', 'you', 'there', 'chelsea' ] },
    'Army Wives':                               { 'words': [ 'army', 'wives' ] },
    'Arrow':                                    { 'words': [ 'arrow' ] },
    'Atlantis':                                 { 'words': [ 'atlantis' ] },
    'Awake':                                    { 'words': [ 'awake' ] },
    'Awkward':                                  { 'words': [ 'awkward' ] },
    'Ax Men':                                   { 'words': [ 'ax', 'men' ] },
    'Babylon':                                  { 'words': [ 'babylon' ] },
    'Back In The Game':                         { 'words': [ 'back', 'in', 'the', 'game' ] },
    'Bad Judge':                                { 'words': [ 'bad', 'judge' ] },
    'Bad Teacher':                              { 'words': [ 'bad', 'teacher' ] },
    'Bang Goes The Theory':                     { 'words': [ 'bang', 'goes', 'the', 'theory' ] },
    'Banshee':                                  { 'words': [ 'banshee' ] },
    'Bates Motel':                              { 'words': [ 'bates', 'motel' ] },
    'Beauty And The Beast':                     { 'words': [ 'beauty', 'and', 'the', 'beast' ] },
    'Becoming Human':                           { 'words': [ 'becoming', 'human' ] },
    'Bedlam':                                   { 'words': [ 'bedlam' ] },
    'Being Eileen':                             { 'words': [ 'being', 'eileen' ] },
    'Being Human (US)':                         { 'words': [ 'being', 'human', 'us' ] },
    'Being Human':                              { 'last': True, 'words': [ 'being', 'human' ] },
    'Being Mary Jane':                          { 'words': [ 'being', 'mary', 'jane' ] },
    'Believe':                                  { 'words': [ 'believe' ] },
    'Ben And Kate':                             { 'words': [ 'ben', 'and', 'kate' ] },
    'Bering Sea Gold Under The Ice':            { 'words': [ 'bering', 'sea', 'gold', 'under', 'the', 'ice' ] },
    'Bering Sea Gold':                          { 'words': [ 'bering', 'sea', 'gold' ] },
    'Best Friends Forever':                     { 'words': [ 'best', 'friends', 'forever' ] },
    'Betrayal':                                 { 'words': [ 'betrayal' ] },
    'Better Of Ted':                            { 'words': [ 'better', 'off', 'ted' ] },
    'Better With You':                          { 'words': [ 'better', 'with', 'you' ] },
    'Big Love':                                 { 'words': [ 'big', 'love' ] },
    'Big Tips Texas':                           { 'words': [ 'big', 'tips', 'texas' ] },
    'Black Sails':                              { 'words': [ 'black', 'sails' ] },
    'Black-ish':                                { 'words': [ 'black', 'ish' ] },
    'Blue Bloods':                              { 'words': [ 'blue', 'bloods' ] },
    'Boardwalk Empire':                         { 'words': [ 'boardwalk', 'empire' ] },
    'Bobs Burgers':                             { 'words': [ 'bob', 'burger'] },
    'Body Of Proof':                            { 'words': [ 'body' ] },
    'Bones':                                    { 'words': [ 'bones' ] },
    'Bored To Death':                           { 'words': [ 'bored', 'to.death' ] },
    'Boss':                                     { 'words': [ 'boss' ] },
    'Boston Med':                               { 'words': [ 'boston', 'med' ] },
    'Bostons Finest':                           { 'words': [ 'boston', 'finest' ] },
    'Breaking Bad':                             { 'words': [ 'breaking', 'bad' ] },
    'Breaking In':                              { 'words': [ 'breaking', 'in' ] },
    'Breakout Kings':                           { 'words': [ 'breakout', 'kings' ] },
    'Breakout':                                 { 'last': True, 'words': [ 'breakout' ] },
    'Britain\'s Really Disgusting Food':        { 'words': [ 'brdf' ] },
    'Broadchurch':                              { 'words': [ 'broadchurch' ] },
    'Brooklyn Nine Nine':                       { 'words': [ 'brooklyn', 'nine' ] },        # TODO: No way to search for two of a single word
    'Brothers And Sisters':                     { 'words': [ 'brothers', 'and', 'sisters' ] },
    'Brothers':                                 { 'last': True, 'words': [ 'brothers' ] },
    'Burn Notice':                              { 'words': [ 'burn', 'notice' ] },
    'CSI Miami':                                { 'words': [ 'csi', 'miami' ] },
    'CSI New York':                             { 'words': [ 'csi', 'ny' ] },
    'CSI':                                      { 'last': True, 'words': [ 'csi' ] },
    'Californication':                          { 'words': [ 'californication' ] },
    'Camelot':                                  { 'words': [ 'camelot' ] },
    'Camp':                                     { 'words': [ 'camp' ] },
    'Caprica':                                  { 'words': [ 'caprica' ] },
    'Castle':                                   { 'words': [ 'castl' ] },
    'Celebrity Rehab With Dr. Drew':            { 'words': [ 'celebrity', 'rehab', 'drew' ] },
    'Chaos':                                    { 'words': [ 'chaos' ] },
    'Charlies Angels':                          { 'words': [ 'charlies', 'angels' ] },
    'Chase':                                    { 'words': [ 'chase' ] },
    'Chasing Mummies':                          { 'words': [ 'chasing', 'mummies' ] },
    'Chicago Fire':                             { 'words': [ 'chicago', 'fire' ] },
    'Chicago PD':                               { 'last': True, 'words': [ 'chicago', 'p', 'd' ] },
    'Childrens Hospital':                       { 'words': [ 'childrens', 'hospital' ] },
    'Chuck':                                    { 'words': [ 'chuck' ] },
    'City Homicide':                            { 'words': [ 'city', 'homicide' ] },
    'Cold Case':                                { 'words': [ 'cold', 'case' ] },
    'Collision':                                { 'words': [ 'collision' ] },
    'Combat Hospital':                          { 'words': [ 'combat', 'hospital' ] },
    'Community':                                { 'words': [ 'community' ] },
    'Constantine':                              { 'words': [ 'constantine' ] },
    'Continuum':                                { 'words': [ 'continuum' ] },
    'Copper':                                   { 'words': [ 'copper' ] },
    'Cosmos - A Space Time Odyssey':            { 'words': [ 'cosmos', 'a', 'space', 'time', 'odyssey' ] },
    'Cougar Town':                              { 'words': [ 'cougar', 'town' ] },
    'Covert Affairs':                           { 'words': [ 'covert', 'affairs' ] },
    'Cracker':                                  { 'words': [ 'cracker' ] },
    'Creature Shop Challenge':                  { 'words': [ 'creature', 'shop', 'challenge' ] },
    'Criminal Minds Suspect Behavior':          { 'words': [ 'criminal', 'minds', 'suspect', 'behav' ] },
    'Criminal Minds':                           { 'last': True, 'words': [ 'criminal', 'minds' ] },
    'Crisis Control':                           { 'words': [ 'crisis', 'control' ] },
    'Crisis':                                   { 'words': [ 'crisis' ] },
    'Cristela':                                 { 'words': [ 'cristela' ] },
    'Crossing Lines':                           { 'words': [ 'crossing', 'lines' ] },
    'Cuckoo':                                   { 'words': [ 'cuckoo' ] },
    'Cult':                                     { 'words': [ 'cult' ] },
    'Curb Your Enthusiasm':                     { 'words': [ 'curb', 'your', 'enthusiasm' ] },
    'Dada':                                     { 'last': True, 'words': [ 'dads' ] },
    'Damages':                                  { 'words': [ 'damages' ] },
    'Dancing On The Edge':                      { 'words': [ 'dancing', 'on', 'the', 'edge' ] },
    'Dancing With The Stars':                   { 'words': [ 'dancing', 'with', 'the', 'stars' ] },
    'Dark Blue':                                { 'words': [ 'dark', 'blue' ] },
    'Deadliest Catch':                          { 'words': [ 'deadliest', 'catch' ] },
    'Defiance':                                 { 'words': [ 'defiance' ] },
    'Desperate Housewives':                     { 'words': [ 'desperate', 'housewives' ] },
    'Detroit 187':                              { 'words': [ 'det' ] },
    'Devious Maids':                            { 'words': [ 'devious', 'maids' ] },
    'Dexter':                                   { 'words': [ 'dexter' ] },
    'Do No Harm':                               { 'words': [ 'do', 'no', 'harm' ] },
    'Doctor Who':                               { 'words': [ 'doctor', 'who', '2005' ] },
    'Dollhouse':                                { 'words': [ 'dollhouse' ] },
    'Dominion':                                 { 'words': [ 'dominion' ] },
    'Downfall':                                 { 'words': [ 'downfall' ] },
    'Dracula':                                  { 'words': [ 'dracula', '2013' ] },
    'Dream House':                              { 'words': [ 'dream', 'house' ] },
    'Dream Machines':                           { 'words': [ 'dream', 'machines' ] },
    'Drop Dead Diva':                           { 'words': [ 'drop', 'dead', 'diva' ] },
    'Eagleheart':                               { 'words': [ 'eagleheart' ] },
    'Eastwick':                                 { 'words': [ 'eastwick' ] },
    'Elementary':                               { 'words': [ 'elementary' ] },
    'Emily Owens M.D.':                         { 'words': [ 'emily', 'owens' ] },
    'Empire':                                   { 'last': True, 'words': [ 'empire' ] },
    'Enlightened':                              { 'words': [ 'enlightened' ] },
    'Episodes':                                 { 'words': [ 'episodes' ] },
    'Eureka':                                   { 'words': [ 'eureka' ] },
    'Extant':                                   { 'words': [ 'extant' ] },
    'Fairly Legal':                             { 'words': [ 'fairly', 'legal' ] },
    'Falling Skies':                            { 'words': [ 'falling', 'skies' ] },
    'Family Guy':                               { 'words': [ 'family', 'guy' ] },
    'Family Tools':                             { 'words': [ 'family', 'tools' ] },
    'Family Tree':                              { 'words': [ 'family', 'tree' ] },
    'Fargo':                                    { 'words': [ 'fargo' ] },
    'Fear Factor':                              { 'words': [ 'fear', 'factor' ] },
    'Finding Bigfoot':                          { 'words': [ 'finding', 'bigfoot' ] },
    'Finding Carter':                           { 'words': [ 'finding', 'carter' ] },
    'Flash Forward':                            { 'words': [ 'flash', 'forward' ] },
    'Flashpoint':                               { 'words': [ 'flash', 'point' ] },
    'Forever':                                  { 'words': [ 'forever' ] },
    'Franklin And Bash':                        { 'words': [ 'franklin', 'and', 'bash' ] },
    'Freakshow':                                { 'words': [ 'freakshow' ] },
    'Free Agents':                              { 'words': [ 'free', 'agents' ] },
    'Friends With Better Lives':                { 'words': [ 'friends', 'with', 'better', 'lives' ] },
    'Fringe':                                   { 'words': [ 'fringe' ] },
    'Funny As Hell':                            { 'words': [ 'funny', 'as', 'hell' ] },
    'Futurama':                                 { 'words': [ 'futurama' ] },
    'Game Of Thrones':                          { 'words': [ 'game', 'of', 'thrones' ] },
    'Gang World':                               { 'words': [ 'gang', 'world' ] },
    'Gary Unmarried':                           { 'words': [ 'gary', 'unmarried' ] },
    'Ghost Lab':                                { 'words': [ 'ghost', 'lab' ] },
    'Ghost Whisperer':                          { 'words': [ 'ghost', 'whisperer' ] },
    'Girl Meets World':                         { 'words': [ 'girl', 'meets', 'world' ] },
    'Girls':                                    { 'last': True, 'words':[ 'girls' ] },
    'Glee':                                     { 'words': [ 'glee' ] },
    'Glue':                                     { 'words': [ 'glue' ] },
    'Good Vibes':                               { 'words': [ 'good', 'vibes' ] },
    'Gossip Girl':                              { 'words': [ 'gossip', 'girl' ] },
    'Gotham':                                   { 'words': [ 'gotham' ] },
    'Graceland':                                { 'words': [ 'graceland' ] },
    'Gracepoint':                               { 'words': [ 'gracepoint' ] },
    'Greek':                                    { 'words': [ 'greek' ] },
    'Greys Anatomy':                            { 'words': [ 'greys', 'anatomy' ] },
    'Grimm':                                    { 'words': [ 'grimm' ] },
    'Ground Floor':                             { 'words': [ 'ground', 'floor' ] },
    'Growing Up Fisher':                        { 'words': [ 'growing', 'up', 'fisher' ] },
    'Hank':                                     { 'words': [ 'hank' ] },
    'Hannibal':                                 { 'words': [ 'hannibal' ] },
    'Happily Divorced':                         { 'words': [ 'happily', 'divorced' ] },
    'Happy Endings':                            { 'words': [ 'happy', 'endings' ] },
    'Happy Town':                               { 'words': [ 'happy', 'town' ] },
    'Happy Valley':                             { 'words': [ 'happy', 'valley' ] },
    'Hard Time':                                { 'words': [ 'hard', 'time' ] },
    'Harrys Law':                               { 'words': [ 'harrys', 'law' ] },
    'Haven':                                    { 'words': [ 'haven' ] },
    'Hawaii Five\'0':                           { 'words': [ 'hawaii', 'five', '0' ] },
    'Hawthorne':                                { 'words': [ 'hawthorne' ] },
    'Heavy':                                    { 'words': [ 'heavy' ] },
    'Helix':                                    { 'words': [ 'helix' ] },
    'Hellcats':                                 { 'words': [ 'hellcats' ] },
    'Hello Ladies':                             { 'words': [ 'hello', 'ladies' ] },
    'Hello Ross':                               { 'words': [ 'hello', 'ross' ] },
    'Hells Kitchen':                            { 'words': [ 'hells', 'kitchen' ] },
    'Hens Behaving Badly':                      { 'words': [ 'hens', 'behaving', 'badly' ] },
    'Heroes':                                   { 'words': [ 'heroes' ] },
    'High School USA':                          { 'words': [ 'high', 'school', 'usa' ] },
    'Highway Patrol':                           { 'words': [ 'highway', 'patrol' ] },
    'Hoarders':                                 { 'words': [ 'hoarders' ] },
    'Homeland':                                 { 'words': [ 'homeland' ] },
    'Hostages':                                 { 'words': [ 'hostages' ] },
    'Hot In Cleveland':                         { 'words': [ 'hot', 'in', 'cleveland' ] },
    'Hotel Stephanie':                          { 'words': [ 'hotel', 'stephanie' ] },
    'House Of Lies':                            { 'words': [ 'house', 'of', 'lies' ] },
    'House':                                    { 'last': True, 'words': [ 'house' ] },
    'How I Met Your Mother':                    { 'words': [ 'how', 'i', 'met', 'your', 'mother' ] },
    'How To Be A Gentleman':                    { 'words': [ 'how', 'to', 'be', 'a', 'gentleman' ] },
    'How To Get Away With Murder':              { 'words': [ 'how', 'to', 'get', 'away', 'with', 'murder' ] },
    'How To Live With Your Parents':            { 'words': [ 'how', 'to', 'live', 'with', 'your', 'parents' ] },
    'Huge':                                     { 'words': [ 'huge' ] },
    'Human Target':                             { 'words': [ 'human', 'targe' ] },
    'Hung':                                     { 'words': [ 'hung' ] },
    'Ice Road Truckers':                        { 'words': [ 'ice', 'road', 'truckers' ] },
    'In Plain Sight':                           { 'words': [ 'in', 'plain', 'sight' ] },
    'In The Flesh':                             { 'words': [ 'in', 'the', 'flesh' ] },
    'In Treatment':                             { 'words': [ 'in', 'treatment' ] },
    'Injustice':                                { 'words': [ 'injustice' ] },
    'Inside Amy Schumer':                       { 'words': [ 'inside', 'amy', 'schumer' ] },
    'Instant Mom':                              { 'words': [ 'instant', 'mom' ] },
    'Intelligence':                             { 'last': True, 'words': [ 'intelligence' ] },
    'Jane By Design':                           { 'words': [ 'jane', 'by', 'design' ] },
    'Jane The Virgin':                          { 'words': [ 'jane', 'the', 'virgin' ] },
    'Jennifer Falls':                           { 'words': [ 'jennifer', 'falls' ] },
    'Justified':                                { 'words': [ 'justified' ] },
    'Kingdom':                                  { 'words': [ 'kingdom' ] },
    'Kirstie':                                  { 'words': [ 'kirstie' ] },
    'Kitchen Nightmares':                       { 'words': [ 'kitchen', 'nightmares' ] },
    'LA Ink':                                   { 'words': [ 'la', 'ink' ] },
    'Last Comic Standing':                      { 'words': [ 'last', 'comic', 'standing' ] },
    'Last Man Standing':                        { 'words': [ 'last', 'man', 'standing' ] },
    'Last Resort':                              { 'words': [ 'last', 'resort' ] },
    'Law And Order CI':                         { 'words': [ 'law', 'and', 'order', 'criminal', 'intent' ] },
    'Law And Order LA':                         { 'words': [ 'law', 'and', 'order', 'la' ] },
    'Law And Order SVU':                        { 'words': [ 'law', 'and', 'order', 's', 'v', 'u' ] },
    'Law And Order UK':                         { 'words': [ 'law', 'and', 'order', 'uk' ] },
    'Law And Order':                            { 'last': True, 'words': [ 'law', 'and', 'order' ] },
    'Legit':                                    { 'words': [ 'legit' ] },
    'Leverage':                                 { 'words': [ 'leverage' ] },
    'Lie To Me':                                { 'words': [ 'lie', 'to', 'me' ] },
    'Life On A Wire':                           { 'words': [ 'life', 'on', 'a', 'wire' ] },
    'Life Unexpected':                          { 'words': [ 'life', 'unexpected' ] },
    'Lights Out':                               { 'words': [ 'lights', 'out' ] },
    'Live To Dance':                            { 'words': [ 'live', 'to', 'dance' ] },
    'Lone Star':                                { 'words': [ 'lone', 'star' ] },
    'Long Island Medium':                       { 'words': [ 'long', 'island', 'medium' ] },
    'Lost':                                     { 'words': [ 'lost' ] },
    'Love Bites':                               { 'words': [ 'love', 'bites' ] },
    'Mad Dogs':                                 { 'words': [ 'mad', 'dogs' ] },
    'Mad Love':                                 { 'words': [ 'mad', 'love' ] },
    'Mad Men':                                  { 'words': [ 'mad', 'men' ] },
    'Madam Secretary':                          { 'words': [ 'madam', 'secretary' ] },
    'Made In Jersey':                           { 'words': [ 'made', 'in', 'jersey' ] },
    'Magic City':                               { 'words': [ 'magic', 'city' ] },
    'Major Crimes':                             { 'words': [ 'major', 'crimes' ] },
    'Man Up':                                   { 'words': [ 'man', 'up' ] },
    'Marry Me':                                 { 'words': [ 'marry', 'me' ] },
    'Marvels Agent Carter':                     { 'words': [ 'marvels', 'agent', 'carter' ] },
    'Marvels Agents Of S.H.I.E.L.D.':           { 'words': [ 'marvels', 'agents', 'of', 's.h.i.e.l.d' ] },
    'Masters Of Sex':                           { 'words': [ 'masters', 'of', 'sex' ] },
    'Matador (US)':                             { 'words': [ 'matador' ] },
    'Medium':                                   { 'words': [ 'medium' ] },
    'Melissa And Joey':                         { 'words': [ 'melissa', 'and', 'joey' ] },
    'Melrose Place':                            { 'words': [ 'melrose', 'place' ] },
    'Memphis Beat':                             { 'words': [ 'memphis', 'beat' ] },
    'Men Of A Certain Age':                     { 'words': [ 'men', 'of', 'a', 'certain', 'age' ] },
    'Mercy':                                    { 'words': [ 'mercy' ] },
    'Merlin':                                   { 'words': [ 'merli' ] },
    'Miami Medical':                            { 'words': [ 'miami', 'medical' ] },
    'Mike And Molly':                           { 'words': [ 'mike', 'and', 'molly' ] },
    'Mind Games':                               { 'words': [ 'mind', 'games' ] },
    'Miranda':                                  { 'words': [ 'miranda' ] },
    'Missing':                                  { 'words': [ 'missing', '2012' ] },
    'Mistresses':                               { 'words': [ 'mistresses' ] },
    'Mixed Britannia':                          { 'words': [ 'mixed', 'britannia' ] },
    'Mob City':                                 { 'words': [ 'mob', 'city' ] },
    'Mockingbird Lane':                         { 'words': [ 'mockingbird', 'lane' ] },
    'Modern Family':                            { 'words': [ 'modern', 'family' ] },
    'Mom':                                      { 'words': [ 'mom' ] },
    'Monday Mornings':                          { 'words': [ 'monday', 'mornings' ] },
    'Mongrels':                                 { 'words': [ 'mongrels' ] },
    'Monk':                                     { 'words': [ 'monk' ] },
    'Motive':                                   { 'words': [ 'motive' ] },
    'Mr. Pickles':                              { 'words': [ 'mr', 'pickles' ] },
    'Mr. Sunshine':                             { 'words': [ 'mr', 'sunshine' ] },
    'Mulaney':                                  { 'words': [ 'mulaney' ] },
    'Murderland':                               { 'words': [ 'murderland' ] },
    'My Babysitters A Vampire':                 { 'words': [ 'my', 'babysitters', 'a', 'vampire' ] },
    'My Boys':                                  { 'words': [ 'my', 'boys' ] },
    'My Generation':                            { 'words': [ 'my', 'generatio' ] },
    'NCIS Los Angeles':                         { 'words': [ 'ncis', 'los', 'angeles' ] },
    'NCIS New Orleans':                         { 'words': [ 'ncis', 'new', 'orleans' ] },
    'NCIS':                                     { 'last': True, 'words': [ 'ncis' ] },
    'NTSF-SD-SUV':                              { 'words': [ 'ntsf', 'sd', 'suv' ] },
    'NYC 22':                                   { 'words': [ 'nyc', '22' ] },
    'Nashville':                                { 'words': { 'nashville' } },
    'Necessary Roughness':                      { 'words': [ 'necessary', 'roughness' ] },
    'New Girl':                                 { 'words': [ 'new', 'girl' ] },
    'Nikita':                                   { 'words': [ 'nikita' ] },
    'Nip Tuck':                                 { 'words': [ 'nip', 'tuck' ] },
    'No Ordinary Family':                       { 'words': [ 'no', 'ordinary', 'family' ] },
    'Numb3rs':                                  { 'words': [ 'numb3rs' ] },
    'Nurse Jackie':                             { 'words': [ 'nurse', 'jackie' ] },
    'Off The Map':                              { 'words': [ 'off', 'the', 'map' ] },
    'Offspring':                                { 'words': [ 'offspring' ] },
    'Once Upon A Time In Wonderland':           { 'words': [ 'once', 'upon', 'a', 'time', 'in', 'wonderland' ] },
    'Once Upon A Time':                         { 'last': True, 'words': [ 'once', 'upon', 'a', 'time' ] },
    'One Tree Hill':                            { 'words': [ 'one', 'tree', 'hill' ] },
    'Orphan Black':                             { 'words': [ 'orphan', 'black' ] },
    'Outlaw':                                   { 'words': [ 'outlaw' ] },
    'Outsourced':                               { 'words': [ 'outsourced' ] },
    'Package Deal':                             { 'words': [ 'package', 'deal' ] },
    'Pan Am':                                   { 'words': [ 'pan', 'am' ] },
    'Parenthood':                               { 'words': [ 'parenthood' ] },
    'Parks And Recreation':                     { 'words': [ 'parks', 'and', 'recreation' ] },
    'Party Down':                               { 'words': [ 'party', 'down' ] },
    'Past Life':                                { 'words': [ 'past', 'life' ] },
    'Perception':                               { 'words': [ 'perception' ] },
    'Perfect Couples':                          { 'words': [ 'perfect', 'couples' ] },
    'Person Of Interest':                       { 'words': [ 'person', 'of', 'interest' ] },
    'Persons Unknown':                          { 'words': [ 'person', 'unknown' ] },
    'Plain Jane':                               { 'words': [ 'plain', 'jane' ] },
    'Political Animals':                        { 'words': [ 'political', 'animals' ] },
    'Portlandia':                               { 'words': [ 'portlandia' ] },
    'Pretty Little Liars':                      { 'words': [ 'pretty', 'little', 'liars' ] },
    'Prey (UK)':                                { 'words': [ 'prey', 'uk' ] },
    'Prime Suspect':                            { 'words': [ 'prime', 'suspect' ] },
    'Primeval New World':                       { 'words': [ 'primeval', 'new', 'world' ] },
    'Primeval':                                 { 'last': True, 'words': [ 'primeval' ] },
    'Private Practice':                         { 'words': [ 'private', 'practice' ] },
    'Psych':                                    { 'words': [ 'psych' ] },
    'Raising Hope':                             { 'words': [ 'raising', 'hope' ] },
    'Rake':                                     { 'words': [ 'rake' ] },
    'Ravenswood':                               { 'words': [ 'ravenswood' ] },
    'Ray Donovan':                              { 'words': [ 'ray', 'donovan' ] },
    'Recjless':                                 { 'words': [ 'reckless' ] },
    'Red Band Society':                         { 'words': [ 'red', 'band', 'society' ] },
    'Redwood Kings':                            { 'words': [ 'redwood', 'kings' ] },
    'Reign':                                    { 'words': [ 'reign' ] },
    'Remember Me':                              { 'words': [ 'remember', 'me' ] },
    'Rescue Me':                                { 'words': [ 'rescue', 'me' ] },
    'Rescue Special Ops':                       { 'words': [ 'rescue', 'special', 'ops' ] },
    'Resurrection':                             { 'words': [ 'resurrection' ] },
    'Retired At 35':                            { 'words': [ 'retired', 'at', '35' ] },
    'Revenge':                                  { 'words': [ 'revenge' ] },
    'Revolution':                               { 'words': [ 'revolution' ] },
    'Ringer':                                   { 'words': [ 'ringer' ] },
    'Rizzoli And Isles':                        { 'words': [ 'rizzoli', 'and', 'isles' ] },
    'Rob':                                      { 'words': [ 'rob' ] },
    'Romantically Challenged':                  { 'words': [ 'romantically', 'challenged' ] },
    'Rookie Blue':                              { 'words': [ 'rookie', 'blue' ] },
    'Royal Navy Caribbean Patrol':              { 'words': [ 'royal', 'navy', 'caribbean', 'patrol' ] },
    'Royal Pains':                              { 'words': [ 'royal', 'pains' ] },
    'Rubicon':                                  { 'words': [ 'rubicon' ] },
    'Rules Of Engagement':                      { 'words': [ 'rules', 'of', 'engagement' ] },
    'Running Wilde':                            { 'words': [ 'running', 'wilde' ] },
    'Rush':                                     { 'last': True, 'words': [ 'rush' ] },
    'Salem':                                    { 'words': [ 'salem' ] },
    'Same Name':                                { 'words': [ 'same', 'name' ] },
    'Sanctuary':                                { 'words': [ 'sanctuary' ] },
    'Satisfaction':                             { 'words': [ 'satisfaction' ] },
    'Saturday Night Live':                      { 'words': [ 'saturday', 'night', 'live' ] },
    'Saving Grace':                             { 'words': [ 'saving', 'grace' ] },
    'Saving Hope':                              { 'words': [ 'saving', 'hope' ] },
    'Scandal':                                  { 'words': [ 'scandal' ] },
    'Scorpion':                                 { 'words': [ 'scorpion' ] },
    'Scoundrels':                               { 'words': [ 'scoundrels' ] },
    'Scrubs':                                   { 'words': [ 'scrubs' ] },
    'Sea Patrol UK':                            { 'words': [ 'sea', 'patrol', 'uk' ] },
    'Sea Patrol':                               { 'words': [ 'sea', 'patrol' ] },
    'Sean Saves The World':                     { 'words': [ 'sean', 'saves', 'the', 'world' ] },
    'Secret Diary Of A Call Girl':              { 'words': [ 'secret', 'diary', 'call', 'girl' ] },
    'Secret Girlfriend':                        { 'words': [ 'secret', 'girl', 'friend' ] },
    'Secret State':                             { 'words': [ 'secret', 'state' ] },
    'Seed':                                     { 'words': [ 'seed' ] },
    'Selfie':                                   { 'words': [ 'selfie' ] },
    'Sex Rehab With Dr. Drew':                  { 'words': [ 'sex', 'rehab', 'drew' ] },
    'Shameless':                                { 'words': [ 'shameless' ] },
    'Sherlock':                                 { 'words': [ 'sherlock' ] },
    'Sherri':                                   { 'words': [ 'sherri' ] },
    'Shit My Dad Says':                         { 'words': [ 'shit', 'my', 'dad', 'says' ] },
    'Silicon Valley':                           { 'words': [ 'silicon', 'valley' ] },
    'Sirens':                                   { 'words': [ 'sirens' ] },
    'Sister Wives':                             { 'words': [ 'sister', 'wives' ] },
    'Skins (US)':                               { 'words': [ 'skins', 'us' ] },
    'Sleepy Hollow':                            { 'words': [ 'sleepy', 'hollow' ] },
    'Smash':                                    { 'words': [ 'smash' ] },
    'Sons Of Anarchy':                          { 'words': [ 'sons', 'of', 'anarchy' ] },
    'Sons Of Tucson':                           { 'words': [ 'sons', 'of', 't' ] },
    'Southland':                                { 'words': [ 'southland' ] },
    'Spartacus Blood And Sand':                 { 'words': [ 'spartacus', 'blood', 'sand' ] },
    'Spartacus Gods Of The Arena':              { 'words': [ 'spartacus', 'gods', 'arena' ] },
    'Spartacus':                                { 'words': [ 'spartacus' ] },
    'Stalker':                                  { 'words': [ 'stalker' ] },
    'Star Wars Rebels':                         { 'words': [ 'star', 'wars', 'rebels' ] },
    'Star Wars The Clone Wars':                 { 'words': [ 'star', 'wars', 'clone', 'wars' ] },
    'Stargate Universe':                        { 'words': [ 'stargate', 'universe' ] },
    'State Of Georgia':                         { 'words': [ 'state', 'of', 'georgia' ] },
    'Steven Seagal Lawman':                     { 'words': [ 'steven', 'seagal', 'law', 'man' ] },
    'Strange Empire':                           { 'words': [ 'strange', 'empire' ] },
    'Suburgatory':                              { 'words': [ 'suburgatory' ] },
    'Summer Camp':                              { 'words': [ 'summer', 'camp' ] },
    'Super Fun Night':                          { 'words': [ 'super', 'fun', 'night' ] },
    'Superjail':                                { 'words': [ 'superjail' ] },
    'Supernanny':                               { 'words': [ 'supernanny' ] },
    'Supernatural':                             { 'words': [ 'super', 'natural' ] },
    'Surviving Jack':                           { 'words': [ 'surviving', 'jack' ] },
    'Survivor':                                 { 'last': True, 'words': [ 'survivor' ] },
    'Survivors':                                { 'words': [ 'survivors', '2008' ] },
    'Switched At Birth':                        { 'words': [ 'switched', 'at', 'birth' ] },
    'Teen Wolf':                                { 'words': [ 'teen', 'wolf' ] },
    'Terra Nova':                               { 'words': [ 'terra', 'nova' ] },
    'Terriers':                                 { 'words': [ 'terriers' ] },
    'The 100':                                  { 'words': [ 'the', '100' ] },
    'The Affair':                               { 'words': [ 'the', 'affair' ] },
    'The Americans':                            { 'words': [ 'the', 'americans' ] },
    'The Big Bang Theory':                      { 'words': [ 'the', 'big', 'bang', 'theory' ] },
    'The Big C':                                { 'last': True, 'words': [ 'the', 'big', 'c' ] },
    'The Blacklist':                            { 'words': [ 'the', 'blacklist' ] },
    'The Bomb Squad':                           { 'words': [ 'the', 'bomb', 'squad' ] },
    'The Borgias':                              { 'words': [ 'the', 'borgias' ] },
    'The Bridge':                               { 'words': [ 'the', 'bridge' ] },
    'The Cape':                                 { 'words': [ 'the', 'cap' ] },
    'The Carrie Diaries':                       { 'words': [ 'the', 'carrie', 'diaries' ] },
    'The Chicago Code':                         { 'words': [ 'chicago', 'code' ] },
    'The Cleveland Show':                       { 'words': [ 'the', 'cleveland', 'show' ] },
    'The Client List':                          { 'words': [ 'the', 'client', 'list' ] },
    'The Closer':                               { 'words': [ 'the', 'closer' ] },
    'The Crazy Ones':                           { 'words': [ 'the', 'crazy', 'ones' ] },
    'The Cult':                                 { 'words': [ 'the', 'cult' ] },
    'The Deep End':                             { 'words': [ 'the', 'deep', 'end' ] },
    'The Defenders':                            { 'words': [ 'the', 'defender' ] },
    'The Event':                                { 'words': [ 'the', 'event' ] },
    'The Exes':                                 { 'words': [ 'the', 'exes' ] },
    'The F Word ':                              { 'words': [ 'tfw' ] },
    'The F Word':                               { 'words': [ 'the', 'f', 'word' ] },
    'The Finder':                               { 'words': [ 'the', 'finder' ] },
    'The Firm':                                 { 'words': [ 'the', 'firm' ] },
    'The Flash':                                { 'words': [ 'the', 'flash' ] },
    'The Following':                            { 'words': [ 'the', 'following' ] },
    'The Forgotten':                            { 'words': [ 'the', 'forgotten' ] },
    'The Fosters':                              { 'words': [ 'the', 'fosters' ] },
    'The Gates':                                { 'words': [ 'the', 'gates' ] },
    'The Glades':                               { 'words': [ 'the', 'glades' ] },
    'The Goldbergs':                            { 'words': [ 'the', 'goldbergs' ] },
    'The Good Guys':                            { 'words': [ 'the', 'good', 'guys' ] },
    'The Good Wife':                            { 'words': [ 'the', 'good', 'wife' ] },
    'The Hard Times Of RJ Berger':              { 'words': [ 'the', 'hard', 'times', 'of', 'r', 'j', 'berger' ] },
    'The Intern':                               { 'words': [ 'the', 'intern' ] },
    'The Killing':                              { 'words': [ 'the', 'killing' ] },
    'The Last Ship':                            { 'words': [ 'the', 'last', 'ship' ] },
    'The Listener':                             { 'words': [ 'the', 'listener' ] },
    'The Lottery':                              { 'words': [ 'the', 'lottery' ] },
    'The Lying Game':                           { 'words': [ 'the', 'lying', 'game' ] },
    'The Marriage Ref':                         { 'words': [ 'the', 'marriage', 'ref' ] },
    'The McCarthy\'s':                          { 'words': [ 'the', 'mccarthys' ] },
    'The Mentalist':                            { 'words': [ 'the', 'mentalist' ] },
    'The Michael J Fox Show':                   { 'words': [ 'the', 'michael', 'j', 'fox', 'show' ] },
    'The Middle':                               { 'words': [ 'the', 'middle' ] },
    'The Millers':                              { 'words': [ 'the', 'millers' ] },
    'The Mindy Project':                        { 'words': [ 'the', 'mindy', 'project' ] },
    'The Missing':                              { 'words': [ 'the', 'missing' ] },
    'The Mob Doctor':                           { 'words': [ 'the', 'mob', 'doctor' ] },
    'The Mysteries Of Laura':                   { 'words': [ 'the', 'mysteries', 'of', 'laura' ] },
    'The Neighbors':                            { 'words': [ 'the', 'neighbors' ] },
    'The New Adventures Of Old Christine':      { 'words': [ 'new', 'adventures', 'old', 'christine' ] },
    'The New Normal':                           { 'words': [ 'the', 'new', 'normal' ] },
    'The Newsroom':                             { 'words': [ 'the', 'newsroom' ] },
    'The Nine Lives Of Chloe King':             { 'words': [ 'the', 'nine', 'lives', 'chloe', 'king' ] },
    'The Office':                               { 'words': [ 'the', 'office', 'u?s?' ] },
    'The Originals':                            { 'words': [ 'the', 'originals' ] },
    'The Paradise':                             { 'words': [ 'the', 'paradise' ] },
    'The Paul Reiser Show':                     { 'words': [ 'the', 'paul', 'r[ie]{2}ser', 'show' ] },
    'The Playboy Club':                         { 'words': [ 'the', 'playbody', 'club' ] },
    'The Protector':                            { 'words': [ 'the', 'protector' ] },
    'The Real L Word':                          { 'words': [ 'the', 'real', 'l', 'word' ] },
    'The River':                                { 'last': True, 'words': [ 'the', 'river' ] },
    'The Sarah Jane Adventures':                { 'words': [ 'sarah', 'jane', 'adventures' ] },
    'The Secret Circle':                        { 'words': [ 'the', 'secret', 'circle' ] },
    'The Secret Life Of The American Teenager': { 'words': [ 'secret', 'life', 'american', 'teenager' ] },
    'The Simpsons':                             { 'words': [ 'the', 'simpsons' ] },
    'The Strain':                               { 'words': [ 'the', 'strain' ] },
    'The Tomorrow People':                      { 'words': [ 'the', 'tomorrow', 'people' ] },
    'The Tudors':                               { 'words': [ 'the', 'tudors' ] },
    'The Tunnel':                               { 'words': [ 'the', 'tunnel' ] },
    'The Vampire Diaries':                      { 'words': [ 'the', 'vampire', 'diaries' ] },
    'The Village':                              { 'words': [ 'the', 'village' ] },
    'The Voice':                                { 'words': [ 'the', 'voice' ] },
    'The Walking Dead':                         { 'words': [ 'the', 'walking', 'dead' ] },
    'The Whole Truth':                          { 'words': [ 'the', 'whole', 'truth' ] },
    'The X Factor':                             { 'words': [ 'the', 'x', 'factor' ] },
    'This Is Not My Life':                      { 'words': [ 'this', 'is', 'not', 'my', 'life' ] },
    'Three Rivers':                             { 'words': [ 'three', 'rivers' ] },
    'Through The Wormhole':                     { 'words': [ 'through', 'wormhole' ] },
    'Thundercats':                              { 'words': [ 'thundercats' ] },
    'Til Death':                                { 'words': [ 'til', 'death' ] },
    'Top Chef Masters':                         { 'words': [ 'top', 'chef', 'masters' ] },
    'Top Chef':                                 { 'words': [ 'top', 'chef' ] },
    'Torchwood':                                { 'words': [ 'torchwood' ] },
    'Total Divas':                              { 'words': [ 'total', 'divas' ] },
    'Touch':                                    { 'words': [ 'touch' ] },
    'Traffic Light':                            { 'words': [ 'traffic', 'light' ] },
    'Trauma':                                   { 'words': [ 'trauma' ] },
    'Treme':                                    { 'words': [ 'treme' ] },
    'Trophy Wife':                              { 'words': [ 'trophy', 'wife' ] },
    'Truckers':                                 { 'words': [ 'truckers' ] },
    'True Blood':                               { 'words': [ 'true', 'blood' ] },
    'True Detective':                           { 'words': [ 'true', 'detective' ] },
    'True Justice':                             { 'words': [ 'true', 'justice' ] },
    'True North':                               { 'words': [ 'true', 'north' ] },
    'Turn':                                     { 'words': [ 'turn' ] },
    'Two And A Half Men':                       { 'words': [ 'two', 'and', 'a', 'half', 'men' ] },
    'Tyrant':                                   { 'words': [ 'tyrant' ] },
    'Ugly Americans':                           { 'words': [ 'ugly', 'americans' ] },
    'Ugly Betty':                               { 'words': [ 'ugly', 'betty' ] },
    'Uncle':                                    { 'last': True, 'words': [ 'uncle' ] },
    'Under The Dome':                           { 'words': [ 'under', 'the', 'dome' ] },
    'Undercover Boss':                          { 'words': [ 'undercover', 'boss' ] },
    'Undercovers':                              { 'words': [ 'undercovers' ] },
    'Underemployed':                            { 'words': [ 'underemployed' ] },
    'Unforgettable':                            { 'words': [ 'unforgettable' ] },
    'United States Of Tara':                    { 'words': [ 'united', 'states', 'of', 'tara' ] },
    'Unsupervised':                             { 'words': [ 'unsupervised' ] },
    'Up All Night':                             { 'words': [ 'up', 'all', 'night' ] },
    'Utopia':                                   { 'words': [ 'utopia' ] },
    'V':                                        { 'words': [ 'v', '2009' ] },
    'Veep':                                     { 'words': [ 'veep' ] },
    'Vegas':                                    { 'words': [ 'vegas' ] },
    'Vikings':                                  { 'words': [ 'vikings' ] },
    'Warehouse 13':                             { 'words': [ 'warehouse', '13' ] },
    'We Are Men':                               { 'words': [ 'we', 'are', 'men' ] },
    'Web Therapy':                              { 'words': [ 'web', 'therapy' ] },
    'Weeds':                                    { 'words': [ 'weeds' ] },
    'Welcome To The Family':                    { 'words': [ 'welcome', 'to', 'the', 'family' ] },
    'White Collar':                             { 'words': [ 'white', 'collar' ] },
    'Whitney':                                  { 'words': [ 'whitney' ] },
    'Wilfred':                                  { 'words': [ 'wilfred' ] },
    'Witches Of East End':                      { 'words': [ 'witches', 'of', 'east', 'end' ] },
    'Working Class':                            { 'words': [ 'working', 'class' ] },
    'You\'re The Worst':                        { 'words': [ 'youre', 'the', 'worst' ] },
    'Z Nation':                                 { 'words': [ 'z', 'nation' ] },
    'Zero Hour':                                { 'words': [ 'zero', 'hour' ] },
    DATEFMT + ' - WWE Friday Night Smackdown.{ext}':  
                                                { 'words': [ 'wwe', 'smackdown' ],
                                                  'extract': [r + '.*\.(?P<ext>(?:avi|mkv|mp4))$' for r in DATES] },
    DATEFMT + ' - WWE Saturday Morning Slam.{ext}':
                                                { 'words': [ 'wwe', 'saturday', 'morning', 'slam' ],
                                                  'extract': [r + '.*\.(?P<ext>(?:avi|mkv|mp4))$' for r in DATES] },
    DATEFMT + ' - WWE Monday Night Raw.{ext}':  { 'words': [ 'wwe', 'raw' ],
                                                  'extract': [r + '.*\.(?P<ext>(?:avi|mkv|mp4))$' for r in DATES] },
    DATEFMT + ' - WWE Main Event.{ext}':        { 'words': [ 'wwe', 'main', 'event' ],
                                                  'extract': [r + '.*\.(?P<ext>(?:avi|mkv|mp4))$' for r in DATES] },
    DATEFMT + ' - iMPACT Wrestling.{ext}':      { 'words': [ 'impact', 'wrestling' ],
                                                  'extract': [r + '.*\.(?P<ext>(?:avi|mkv|mp4))$' for r in DATES] }
    }

db.drop_all()
db.create_all()
s = db.session()
i = 0
for name,items in SimpleRenameList.items():
    if 'extract' in items:
        r = RegexModel(title=name,
                       extractDefault=False,
                       identifyDefault=True,
                       renameDefault=False,
                       # TODO:  This field should be converted into MULTIPLE regexes ...
                       extract=items['extract'],
                       identify=','.join(items['words']),
                       rename=name)
    else:
        if 'words' in items:
            identify = ','.join(items['words'])
        else:
            identify = ','.join([word.lower() for word in name.split(' ')])
        r = RegexModel(title=name,
                       extractDefault=True,
                       identifyDefault=True,
                       renameDefault=True,
                       extract=None,
                       identify=identify,
                       rename=name)
    f = FeedModel(title=name, regexes=[r])
    s.add(f)
    s.commit()
    i += 1

sys.exit(0)



class RenameShow:
    split = re.compile(r".*\b[s]?(\d{1,2})[ex]?(\d{2})\b.*(mp4|mkv|avi)$", re.IGNORECASE)
    split2 = re.compile(r".*\b[s]?(\d{1,2})[ex]?(\d{2})e?(\d{2})\b.*(mp4|mkv|avi)$", re.IGNORECASE)

    _PERCENT = 0
    _FORMAT = 1

    def __init__(self, identify, replacement, extract = None):
        expr = '^.*' + '.*'.join(identify) + '.*$'
        self.identify = re.compile(expr, re.IGNORECASE)
        self.replacement = replacement
        if extract is None:
            self.extract = [self.split, self.split2]
            self.rfmt = self._PERCENT
        else:
            if type(extract) is list:
                self.extract = [re.compile('^.*' + e) for e in extract]
                self.rfmt = self._FORMAT
            else:   # TODO: is re?
                self.extract = re.compile(extract)
                self.rfmt = self._PERCENT

    def RenameIf(self, filename):
        m = self.identify.match(filename)
        if m:
            if self.rfmt == self._PERCENT:
                for e in self.extract:
                    m = e.search(filename)
                    if m:
                        if len(m.groups()) > 3:
                            return self.replacement + ' - S%02dE%02d-E%02d.%s' % tuple(self._normalizeExtracted(m.groups()))
                        else:
                            return self.replacement + ' - S%02dE%02d.%s' % tuple(self._normalizeExtracted(m.groups()))
                print("echo [INT] Show known, but cannot detect season and episode: " + filename)
            else:
                for e in self.extract:
                    m = e.match(filename)
                    if m:
                        return self.replacement.format(**self._normalizeExtracted(m.groupdict()))
                print("echo [EXT] Show known, but cannot detect season and episode: " + filename)

        return None

    def _normalizeExtracted(self, fields):
        if type(fields) is dict:
            f = {}
            for g in fields.keys():
                if fields[g].isdigit():
                    f[g] = int(fields[g])
                else:
                    f[g] = fields[g]
        else:
            f = []
            for g in fields:
                if g.isdigit():
                    f.append(int(g))
                else:
                   f.append(g)
        return f

    def __repr__(self):
        if self.rfmt == self._FORMAT:
            e = '[ '
            c = ''
            for p in self.extract:
                e += '%s%s' % (c, p.pattern)
                c = ',\n\t\t'
            e += ' ]'
        else:
            e = self.extract.pattern
        return "{\n\t'extract': %s,\n\t'identify': %s,\n\t'replacement': %s,\n\t'rfmt': %s\n}" % \
                ( e, self.identify.pattern, self.replacement, self.rfmt )

RenameList = []

# Create the simple rename regex's
for name,items in SimpleRenameList.items():
    #exp = '^.*'
    if 'last' not in items or items['last'] == False:
        #for n in items['words']:
        #    exp += n + '.*'
        #exp += '(?:.*20[01][0-9])?.*?(?!264|720p|187)s?(\d?\d)(?:e|x)?(\d\d).*(avi|mkv|mp4)$'
        if 'extract' in items:
            obj = RenameShow(items['words'], name, items['extract'])
        else:
            obj = RenameShow(items['words'], name)
        RenameList.append(obj)

# Create the simple rename regex's that are required to be after the
# others
for name,items in SimpleRenameList.items():
    if 'last' in items and items['last'] == True:
        if 'extract' in items:
            obj = RenameShow(items['words'], name, items['extract'])
        else:
            obj = RenameShow(items['words'], name)
        RenameList.append(obj)

# Execute the renames
testing = len(sys.argv) > 1
for e in ('*.mp4', '*.avi', '*.mkv'):
    for f in glob.glob(e):
        found = False
        for r in RenameList:
            o = r.RenameIf(f)
            if o:
                found = True
                if f != o:
                    if testing:
                        break
                    print('mv "%s" "%s"' % (f, o))
                    break
        if not found:
            if testing:
                print('Unknown: {0}'.format(f))
            else:
                print('echo "Unknown: {0}"'.format(f))

TODO="""
Table Shows: id (unique), title (final name of converted show title, overridable)
Table Identify: show_id (from Shows), sequence, regex?, criteria
Table Extract: show_id, sequence
Table Rename: show_id, sequence

"""

