Example #1
0
	def testMovieWeekend(self):
		m = Movie(121, "Saturday", True, True)

		m.addTicket(20,False)
		price = m.finishPurchase()

		self.assertEquals(price, 17.0)
class MovieTest(unittest.TestCase):
    def setUp(self):
        self.movie = Movie("Test Movie", 5)

    def test_create_movie_get_name_and_rating(self):
        self.assertEqual("Test Movie", self.movie.get_name())
        self.assertEqual(5, self.movie.get_rating())
Example #3
0
        def loadActors(self, count=100):
                """function to read actors data and create a relationship between actors and movie."""

                actors = self.readArtists("actor", count)
                self.filePointerActors = self.fileHandleActors.tell()

                objActor = Actor("", 0)
                objMovie = Movie("", "", 0)

                for actor in actors:
                        name, title, year = actor
                        
                        # check if actor does not exist else create ID
                        if objActor.getArtistByName(name, self.actorsList) == None:
                                self.artistCounter += 1
                                actorId = self.artistCounter
                                newActor = Actor(actorId, name)
                                self.actorsList.append(newActor)
                                
                                # searches the movie list to check if movies have not been already visualized
                                if not objMovie.doesMovieExist(title, self.moviesList) and \
                                   objMovie.getMovieByName(title, self.moviesList) == None:
                                        self.movieCounter += 1
                                        movieId = self.movieCounter
                                        movie = Movie(movieId, title, year)
                                        self.moviesList.append(movie)

                                        # create relation between actor and  movie
                                        relation = ArtistMovieRelation(actorId, movieId)
                                        self.relationsList.append(relation)
Example #4
0
        def loadActresses(self, count=100):	
                """function to read actresses data and create a relationship between actress and movie,"""

                # read actresses from file
                actresses = self.readArtists("actress", count)
                self.filePointerActresses = self.fileHandleActresses.tell()
                objActress = Actress("", 0)
                objMovie = Movie("", "", 0)

                for actress in actresses:
                        name, title, year = actress
                        actress = objActress.getArtistByName(name, self.actressesList)

                        # check if actress already not exist then add it
                        if actress == None:
                                self.artistCounter += 1
                                actressId = self.artistCounter
                                newActress = Actress(actressId, name)
                                self.actressesList.append(newActress)
                        else:
                                actressId = actress.getArtistId()

                        # check if movie already exists. only if the movie doesn't exist, it will create an ID and 
                        if not objMovie.doesMovieExist(title, self.moviesList) and \
                           objMovie.getMovieByName(title, self.moviesList) == None:
                                self.movieCounter += 1
                                movieId = self.movieCounter
                                movie = Movie(movieId, title, year)
                                self.moviesList.append(movie)

                                # create relation between actor and  movie
                                relation = ArtistMovieRelation(actressId, movieId)

                                self.relationsList.append(relation)
Example #5
0
        def onObjectClick(self, event): 
                """function to get movie details on the movie when clicked."""
                

                tempMovie = Movie(2, 4, "132")
                tempMovie = tempMovie.getMovieByOvalId(event.widget.find_closest(event.x, event.y)[0], self.moviesList)

                # get id's of the artists starring in this movie
                artistmovierelation = ArtistMovieRelation(0,0)
                artistStarring = artistmovierelation.getArtistsByMovieId(tempMovie.getMovieId(), self.relationsList)

                tempActor = Actor("","")
                tempActress = Actress("","")

                # fetches the name of the actor or actress. finds out whether it originated from tbe actor or actress class.

                artistsStartingNames = []
                for artistId in artistStarring:
                        actor = tempActor.getArtistByid(artistId, self.actorsList)
                        if actor != None:
                                artistsStartingNames.append(actor.getArtistName())
                        else:
                                actress = tempActress.getArtistByid(artistId, self.actressesList)
                                if actress != None:
                                        artistsStartingNames.append(actress.getArtistName())

                #  labels to show the film details
                self.movieDetailsVar.set('Title of the Film   : ' + tempMovie.getMovieTitle() + "\n" + "\n" 
                                         "Year Film Released : " + tempMovie.getMovieYear() + "\n"+ "\n" 
                                         "Actor/Actress Name  : " + ", ".join(artistsStartingNames))
Example #6
0
	def testGoingWithLotsOfPeopleOnThursday(self):
		m = Movie(110, "Thursday", True, True)
		
		for i in range(30):
			m.addTicket(20+i,True)
		
		price = m.finishPurchase()
		self.assertEquals(price,30 * 9)
class TestMovieClass(unittest.TestCase):
    def setUp(self):
        self.m = Movie("Best.Movie.Ever.", 2014, 10)

    def test_get_movie_title(self):
        self.assertEqual("Best.Movie.Ever.", self.m.get_title())

    def test_get_movie_year(self):
        self.assertEqual(2014, self.m.get_year())

    def test_get_movie_rating(self):
        self.assertEqual(10, self.m.get_rating())

    @unittest.skip("This works but no point in generating extra movies.")
    def test_save_movie(self):
        self.assertTrue(self.m.save())
Example #8
0
 def getMovieInfoByTMDB_ID(self, tmdb_id=''):
     self.domain = 'movie'
     self.action = 'getInfo'
     if tmdb_id:
         self.tmdb_id = tmdb_id
     
     try:    
         movie_list = Movie.select(Movie.q.tmdb_id==self.tmdb_id)
         if movie_list.count() == 1:
             oMovie = movie_list[0]
         elif movie_list.count() == 0:
             raise SQLObjectNotFound
         else:
             raise AttributeError
     except SQLObjectNotFound:
     
         self.url = "%s%s" % (self.urls.generateURL(self.domain, self.action), self.tmdb_id)        
         self.movie_info = self._getResponse(self.url)
                 
         oMovie = Movie(tmdb_id = self._getKey('id', 0),
                        imdb_id = self._getKey('imdb_id', ''),
                        title = self._getKey('name', ''),
                        year = int(self._getYearFromDate(self._getKey('released', ''))),
                        genre = self._getPrimaryGenre(self._getKey('genres', [])),
                        mpaa = Movie.ratings.index(self._getKey('certification', 'NR')),
                        director = self._getDirector(self._getKey('cast', [])),
                        actors = self._getPrimaryActors(self._getKey('cast', [])),
                        description = self._getKey('overview', ''),
                        length = int(self._getKey('runtime', 0)),
                        poster_URL = self._getPosterURL(self._getKey('posters', '')),
                        )
     
     return oMovie
Example #9
0
    def _loadFactory(self):
        if len(self._plugins) <= 0:
            return

        self._factory = fact.Factory(Movie.getTypeName())
        for plug in self._plugins:
            self._factory.addModule(plug)
class TestMovie(unittest.TestCase):
    """Tests for movie objects"""
    def setUp(self):
        self.movie = Movie('../test.mkv')

    def test_get_extension(self):
        self.assertEqual('.mkv', self.movie.get_extension())

    def test_get_filename(self):
        self.assertEqual('test', self.movie.get_filename())

    def test_get_title(self):
        self.assertEqual(None, self.movie.get_title())

    def test_get_duration(self):
        self.assertEqual('0:21:37', self.movie.get_duration())
Example #11
0
 def load_movies(self):
     self.cursor.execute("SELECT * FROM movies")
     unparsed_movies = self.cursor.fetchall()
     movies = {}
     if unparsed_movies:
         for unparsed_movie in unparsed_movies:
             #get info from database
             movie_id = unparsed_movie[0]
             title = unparsed_movie[1]
             year = unparsed_movie[2]
             rating = unparsed_movie[3]
             #create a new Movie object and add it to {movie_id: Movie}
             movie = Movie(title, year, rating)
             movie.cast = self.get_actors_in_movie(int(movie_id))
             movies[movie_id] = movie
     return movies
Example #12
0
    def get_top_movies(self, top_x, min_ratings):
        movie_rows_list = Movie.read_movie_file()

        movie_list_with_min_ratings = []
        for movie in movie_rows_list:
            movie_id = movie[0]
            movie_name = movie[1]

            ratings_list = self.get_movie_rating_list(movie_id)
            # print("movie_id", movie_id)
            # print("ratings", ratings_list)

            if len(ratings_list) >= min_ratings:
                movie_avg_tup = (movie_id, movie_name, self.get_avg_rating(movie_id))
                movie_list_with_min_ratings.append(movie_avg_tup)

        sorted_list = sorted(movie_list_with_min_ratings, key = lambda x: x[2])
        reversed_list = list(reversed(sorted_list))
        # print(sorted_list)
        # print(reversed_list)

        top_x_list = reversed_list[:top_x]
        #print(top_x_list)

        return top_x_list
Example #13
0
 def __init__(self, movie_name):
     super(Controller, self).__init__()
     self.session = login()
     self.movie_name = movie_name
     self.movie = Movie(self.movie_name, self.session)
     #self.url = 'http://s.weibo.com/weibo/'
     self.url = 'http://s.weibo.com/wb/'
     self.page_count = 0
Example #14
0
	def find_movie(self,user_action):
		self.header_output("Finding....")
		print "\n Example: find iron or find Iron Man 3 \n"
		movies = Movie.read_movies_from_file()
		if user_action != []:
			arg    = user_action.pop(0)
			found  = [x for x in movies if self.search(x,arg)]
			self.movie_table_output(found)
Example #15
0
class Controller(object):
    """docstring for Controller"""
    def __init__(self, movie_name):
        super(Controller, self).__init__()
        self.session = login()
        self.movie_name = movie_name
        self.movie = Movie(self.movie_name, self.session)

    def start(self):
        start_time = datetime.datetime.strptime(START_TIME, '%Y-%m-%d-%H')
        end_time = datetime.datetime.strptime(END_TIME, '%Y-%m-%d-%H')
        if start_time < end_time:
            while True:
                time.sleep(3)
                cursor_time = start_time + datetime.timedelta(hours=1)
                timescope = datetime.datetime.strftime(start_time, '%Y-%m-%d-%H') +':' + datetime.datetime.strftime(cursor_time, '%Y-%m-%d-%H')
                url = 'http://s.weibo.com/weibo/'+ quote(self.movie_name) +'&timescope=custom:'+ quote(timescope)
                response = self.session.get(url)
                count = self.get_page_count(response.content)
                self.handle_one_page(url, count, self.movie.id)
                start_time = cursor_time
                if start_time > end_time:
                    break
        else:
            print 'ERROR:Start time must early than end time!'

    def get_page_count(self, content):
        max_count = 0
        result = re.findall(r'&page=\d+', content)
        for index in result:
            info = index.split('=')
            if int(info[1]) > max_count:
                max_count = int(info[1])
        print 'max_page:', max_count
        return max_count

    def handle_one_page(self, url_head, page_count, movie_id):
        for i in xrange(1, page_count + 1):
            page = str(i)
            url = url_head +"&page=" + page
            response = self.session.get(url)
            self.movie.decode_content(response.content, movie_id)
            print "现在是第%s页" % page
            time.sleep(3)
Example #16
0
	def add(self):
		args = []
		self.header_output("Adding....")
		args.append(raw_input("Enter Movie Name: ").strip())
		args.append(raw_input("Enter Release year: ").strip())
		args.append(raw_input("Enter Movie Rating: ").strip())
		if Movie.add_movie_into_file(args):
			print("\nNew movie has been added to your movie list")
		else:
			print("\nSorry File Error!")
Example #17
0
def rename(filename):
	filename_without_extension = filename
	extension = ""
	
	if os.path.isdir(filename) == False: 
		filename_without_extension, extension = os.path.splitext(filename)
	    
	query = ImdbQuery.create_query_from_filename(filename_without_extension)
	movie = Movie.create_movie_from_imdb_query(query)
	if movie.title == "None":
#		sys.stdout.write("Query Was: " + query + "\n")
		return "None"
		
	return unicode(movie).encode("utf-8") + extension
Example #18
0
 def load_movies_run(self, filepaths):
     renaming_rule = utils.preferences.value("renaming_rule").toString()
     # loop on file paths
     for filepath in filepaths:
         # set loading label text, show current file name
         self.ui.label_loading.setText(QApplication.translate('GUI', "Getting information from ")\
                                        + os.path.split(filepath)[1])
         # create a new movie object
         movie = Movie(filepath)
         # generate new movie name based on renaming rule
         movie.generate_new_name(renaming_rule)
         # add movie to list
         self.movies.append(movie)
         # insert a new row in movie table
         self.ui.table_movies.insertRow(self.ui.table_movies.rowCount())
         # create a table item with original movie file name
         item_original_name = QTableWidgetItem(movie.original_file_name())
         item_original_name.setForeground(QBrush(Qt.black))
         self.ui.table_movies.setItem(self.ui.table_movies.rowCount() - 1, 0, item_original_name)
         # create a table item with new movie file name
         item_new_name = QTableWidgetItem(movie.new_file_name())
         item_new_name.setForeground(QBrush(Qt.black))
         self.ui.table_movies.setItem(self.ui.table_movies.rowCount() - 1, 1, item_new_name)
     self.load_movies_finished.emit()
Example #19
0
def save_to_ndb(movie_dic):
    save_num = 0

    for m in movie_dic:
        if Movie.query(Movie.name_md5 == m['name_md5']).count() == 0:
            Movie(
                    name_md5=m['name_md5'],
                    name=m['name'],
                    content=m['content'],
                    info=m['info'],
                    href=m['href'],
                    is_email='no'
                ).put()
            save_num += 1
            
    return save_num
Example #20
0
 def handle_starttag(self, tag, attrs):
     if tag == 'div':
         for attr in attrs:
             if attr[0] == 'class' and attr[1] == 'info':
                 # <div class="info"> starts a new movie entry.
                 self._output_entry = True
                 self._movie = Movie()
                 self._output_entry_finish_tag = tag
     elif self._output_entry:
         if tag == 'li':
             for attr in attrs:
                 if attr[0] == 'class' and attr[1] == 'title':
                     # <li class="title"> includes movie name
                     self._start_movie_name = True
                 elif attr[0] == 'class' and attr[1] == 'intro':
                     # <li class="intro"> includes movie intro
                     self._output_finish_tag = tag
                     self._grab_data = True
                     self._start_intro = True
         elif tag == 'span':
             for attr in attrs:
                 if attr[0] == 'class' and attr[1] == 'date':
                     # <span class="date"> includes movie view date.
                     self._output_finish_tag = tag
                     self._grab_data = True
                     self._start_date = True
                     #TODO
                     # watched list has
                     #     <dev class="info">
                     #       everything
                     #     </dev>
                     # but wish list has
                     #     <dev class="info">
                     #        movie info
                     #     </dev>
                     #     <li>
                     #        entry creation day
                     #     </li>
                 if attr[0] == 'class' and attr[1].find('rating') >= 0:
                     # <span class="ratingX-t"> has rating information.
                     def GetRating(s):
                         return ((s.split('rating'))[1].split('-'))[0]
                     self._movie.set_rating(int(GetRating(attr[1])))
         elif self._start_movie_name and tag == MOVIE_NAME_START_TAG:
             # movie name tag is encountered. Store next data.
             self._output_finish_tag = tag
             self._grab_data = True
Example #21
0
	def list_movie(self,kwargs):
		print "\n Example: list name, list rating, list date or list by name etc. \n"
		sort_order = 'name'
		if kwargs != []:
			if kwargs[0] == 'by':
				sort_order = kwargs.pop(1)
			else: 
				sort_order = kwargs.pop(0)
		
		movies = Movie.read_movies_from_file()
		if sort_order == 'date':
			movies.sort(cmp = lambda x, y: cmp(x.date, y.date))
		elif sort_order == 'rating':
			movies.sort(cmp = lambda x, y: cmp(x.rating, y.rating))			
		else:
			movies.sort(cmp = lambda x, y: cmp(x.movie, y.movie))
		self.movie_table_output(movies)
Example #22
0
    def getMovieIDByName(self, name):
        self.domain = 'movie'
        self.action = 'search'
        self.searchTerm = quote_plus(name)
        
        try:
            movie_list = Movie.select("""movie.title LIKE '%s'""" % name)
            if movie_list.count() == 1:
                self.tmdb_id = movie_list[0].tmdb_id
            else:
                raise SQLObjectNotFound
        except SQLObjectNotFound:
            self.url = "%s%s" % (self.urls.generateURL(self.domain, self.action), self.searchTerm)

            movie_info = self._getResponse(self.url)
            self.tmdb_id = movie_info['id']
        
        return self.tmdb_id
Example #23
0
def load(fn=None):
  if fn == None:
    print "filename required."
    return
  else:
    with open(fn, "r") as f:
      try:
        movies = json.load(f)['movies']
      except KeyError:
        print "json file must have a top level key 'movies'"
        return

  accessor = {}
  ms = []
  for m in movies:
     ms.append(Movie.load(m))
     accessor[m['title']] = ms[-1]

  calculate(ms)
  return ms, accessor
 def add_movie(self):
     self.movie_title = input('title >')
     self.movie_year = input('year >')
     while True:
         self.movie_rating = int(input('rating >'))
         if self.movie_rating <= 10 and self.movie_rating > 0:
             break
         else:
             print("Rating can only be a number between 1 and 10.")
     self.m = Movie(self.movie_title,
                    self.movie_year,
                    self.movie_rating)
     if(self.m.get_title() not in self.movies.keys()
        and self.m.get_year() not in self.movies.values()):
         self.movies[self.movie_title] = self.movie_year
         self.m.save()
         print('{} ({}) {}'.format(self.movie_title,
                                   self.movie_year,
                                   'was added to your catalog!'))
     else:
         print('Movie already exists!')
Example #25
0
 def _processListRequest(self):
     """ Process a list Request. """
     log.level = -1
     listItems = []
     for dirName in sorted(os.listdir(self.baseDir)):
         if (os.path.isdir(dirName)):
             dirPath = "%s/%s" % (self.baseDir, dirName)
             movie = Movie(dirPath)
             if   (self.list == 'novideo'): listItems += movie.getNoVideoList()
             elif (self.list == 'badnfo'):  listItems += movie.getBadNfoList()
             elif (self.list == 'nonfo'):   listItems += movie.getMissingNfoList()
             elif (self.list == 'hassub'):  listItems += movie.getHasSubtitleList()
             elif (self.list == 'nosub'):   listItems += movie.getNoSubtitleList()
             elif (self.list == 'suberr'):  listItems += movie.getSubtitleErrorList()
     # Print the Result
     if (listItems) and (self.print0):
         sys.stdout.write("\0".join(listItems))
     elif (listItems):
         print "\n".join(listItems)
Example #26
0
        def loadMoreMovies(self):
                """function to load more movies"""
                
                self.loadActors(self.moviesToLoadEachTime)

                self.loadActresses(self.moviesToLoadEachTime)
                

                if self.moviesDrawnCount < len(self.moviesList):
                        
                        for i in range(self.moviesDrawnCount, len(self.moviesList)):
                                
                                titleOfMovie=((Movie.getMovieTitle(self.moviesList[i])))
                                #adds the title of the movie to the movieNames array.
                                self.movieNames.append(titleOfMovie)
                                
                                
                                # generate random x-axis and y-axis for the ellipses
                                
                                x = random.randint(10, 800)

                                y = random.randint(10, 420)

                                # draw ellipses on the circle
                                oval = self.canvas.create_oval(x, y, x + 20, y + 20, outline="gold", fill="black", width=1)
                                
                                # keep a reference of the oval 


                                self.moviesList[i].setOvalId(oval)
                                self.canvas.tag_bind(oval, '<Button-1>', self.onObjectClick)
                        self.cls()
                        
                        self.Sort(self.movieNames)  
        
                        self.moviesDrawnCount += len(self.moviesList) - self.moviesDrawnCount
Example #27
0
    def __init__(self, parent, preferences_dialog):
        QDialog.__init__(self, parent)

        self.ui = loadUi("renaming_rule_dialog.ui", self)

        self.ui.preferences_dialog = preferences_dialog

        # creates an example movie, used to test the renaming rule
        self.example_movie = Movie()

        self.populate_list_visual_rule()
        self.update_representations()
        renaming_rule = utils.preferences.value("renaming_rule").toString()
        self.update_example_movie(renaming_rule)

        ## slots connection
        self.ui.list_visual_rule.model().rowsInserted.connect(self.rule_changed)
        self.ui.list_visual_rule.model().rowsRemoved.connect(self.rule_changed)

        self.ui.button_remove_rule.clicked.connect(self.remove_rule)
        self.ui.button_clean_rule.clicked.connect(self.clean_rule)

        self.ui.button_add_title.clicked.connect(self.add_title)
        self.ui.button_add_original_title.clicked.connect(self.add_original_title)
        self.ui.button_add_year.clicked.connect(self.add_year)
        self.ui.button_add_director.clicked.connect(self.add_director)
        self.ui.button_add_duration.clicked.connect(self.add_duration)
        self.ui.button_add_language.clicked.connect(self.add_language)

        self.ui.button_add_round_brackets.clicked.connect(self.add_round_brackets)
        self.ui.button_add_square_brackets.clicked.connect(self.add_square_brackets)
        self.ui.button_add_curly_brackets.clicked.connect(self.add_curly_brackets)

        self.ui.button_show_preferences.clicked.connect(self.show_preferences)

        self.ui.button_close.clicked.connect(self.close)
        frame = frame[npx/2:npx/2+cutoff,:]
        sz,sx = frame.shape
        if iframe==0:
            stack = np.zeros((N_frames,sz,sx),dtype=np.complex64)
        stack[iframe,:,:] = frame


    astack = np.abs(stack)
    smax = np.max(stack)
    smin = np.min(stack)

    avifn = os.path.join(frame_dir,'frames.avi')
    make_movie = not os.path.exists(avifn)

    if make_movie:
        mov = Movie(avifn)
        fig = plt.figure()

        for k in range(N_frames):
            plt.cla()
            plt.imshow(astack[k,:,:],interpolation='none',aspect='auto')
            plt.clim((smin,smax))
            if k==0:
                plt.colorbar()
            mov.add(fig)
            plt.pause(.1)

        mov.make()


    sz,sy,sx = stack.shape
import csv
from movie import Movie
from user import User

movies = Movie.read_movies('u.item')

users = User.read_users('u.user')

class Rating:
    def __init__(self, user_id, movie_id, score):
        self.user_id = user_id
        self.movie_id = movie_id
        self.score = score

def add_rating(rating):
    movie = movies[movie_id]
    movie.add_rating(rating)

    user = users[user_id]
    user.add_rating(rating)

with open('u.data', 'r') as movies_file:
    reader = csv.DictReader(movies_file, fieldnames=['user_id', 'movie_id', 'score'], delimiter='\t')
    for row in reader:
        user_id = row['user_id']
        movie_id = row['movie_id']
        score = row['score']

        rating = Rating(user_id, movie_id, score)

        add_rating(rating)
Example #30
0
class RenamingRuleDialog(QDialog):

    TITLE = QApplication.translate('RenamingRuleDialog', "Title")
    ORIGINAL_TITLE = QApplication.translate('RenamingRuleDialog', "Original title")
    YEAR = QApplication.translate('RenamingRuleDialog', "Year")
    DIRECTOR = QApplication.translate('RenamingRuleDialog', "Director")
    DURATION = QApplication.translate('RenamingRuleDialog', "Duration")
    LANGUAGE = QApplication.translate('RenamingRuleDialog', "Language")
    OPENED_ROUND_BRACKET = "("
    CLOSED_ROUND_BRACKET = ")"
    OPENED_SQUARE_BRACKET = "["
    CLOSED_SQUARE_BRACKET = "]"
    OPENED_CURLY_BRACKET = "{"
    CLOSED_CURLY_BRACKET = "}"

    RENAMING_TO_VISUAL_RULE = {
        Movie.TITLE:TITLE,
        Movie.ORIGINAL_TITLE:ORIGINAL_TITLE,
        Movie.YEAR:YEAR,
        Movie.DIRECTOR:DIRECTOR,
        Movie.DURATION:DURATION,
        Movie.LANGUAGE:LANGUAGE,
        OPENED_ROUND_BRACKET:OPENED_ROUND_BRACKET,
        CLOSED_ROUND_BRACKET:CLOSED_ROUND_BRACKET,
        OPENED_SQUARE_BRACKET:OPENED_SQUARE_BRACKET,
        CLOSED_SQUARE_BRACKET:CLOSED_SQUARE_BRACKET,
        OPENED_CURLY_BRACKET:OPENED_CURLY_BRACKET,
        CLOSED_CURLY_BRACKET:CLOSED_CURLY_BRACKET
    }

    VISUAL_TO_RENAMING_RULE = {
       TITLE:Movie.TITLE,
       ORIGINAL_TITLE:Movie.ORIGINAL_TITLE,
       YEAR:Movie.YEAR,
       DIRECTOR:Movie.DIRECTOR,
       DURATION:Movie.DURATION,
       LANGUAGE:Movie.LANGUAGE,
       OPENED_ROUND_BRACKET:OPENED_ROUND_BRACKET,
       CLOSED_ROUND_BRACKET:CLOSED_ROUND_BRACKET,
       OPENED_SQUARE_BRACKET:OPENED_SQUARE_BRACKET,
       CLOSED_SQUARE_BRACKET:CLOSED_SQUARE_BRACKET,
       OPENED_CURLY_BRACKET:OPENED_CURLY_BRACKET,
       CLOSED_CURLY_BRACKET:CLOSED_CURLY_BRACKET
   }

    def __init__(self, parent, preferences_dialog):
        QDialog.__init__(self, parent)

        self.ui = loadUi("renaming_rule_dialog.ui", self)

        self.ui.preferences_dialog = preferences_dialog

        # creates an example movie, used to test the renaming rule
        self.example_movie = Movie()

        self.populate_list_visual_rule()
        self.update_representations()
        renaming_rule = utils.preferences.value("renaming_rule").toString()
        self.update_example_movie(renaming_rule)

        ## slots connection
        self.ui.list_visual_rule.model().rowsInserted.connect(self.rule_changed)
        self.ui.list_visual_rule.model().rowsRemoved.connect(self.rule_changed)

        self.ui.button_remove_rule.clicked.connect(self.remove_rule)
        self.ui.button_clean_rule.clicked.connect(self.clean_rule)

        self.ui.button_add_title.clicked.connect(self.add_title)
        self.ui.button_add_original_title.clicked.connect(self.add_original_title)
        self.ui.button_add_year.clicked.connect(self.add_year)
        self.ui.button_add_director.clicked.connect(self.add_director)
        self.ui.button_add_duration.clicked.connect(self.add_duration)
        self.ui.button_add_language.clicked.connect(self.add_language)

        self.ui.button_add_round_brackets.clicked.connect(self.add_round_brackets)
        self.ui.button_add_square_brackets.clicked.connect(self.add_square_brackets)
        self.ui.button_add_curly_brackets.clicked.connect(self.add_curly_brackets)

        self.ui.button_show_preferences.clicked.connect(self.show_preferences)

        self.ui.button_close.clicked.connect(self.close)

    def populate_list_visual_rule(self):
        """
        populate renaming rule by rule read from settings
        """

        renaming_rule = utils.preferences.value("renaming_rule").toString()
        # split rule
        rules = renaming_rule.split('.')
        # if rule is empty, reset it to 'title'
        if rules[0] == '':
            rules[0] = Movie.TITLE
            renaming_rule = Movie.TITLE
            utils.preferences.setValue("renaming_rule", renaming_rule)
        visual_rule = []
        # loop on rules
        for rule in rules:
            visual_rule.append(self.RENAMING_TO_VISUAL_RULE[rule])
        self.ui.list_visual_rule.addItems(visual_rule)

    def update_representations(self):
        duration_index = utils.preferences.value("duration_representation").toInt()[0]
        duration_representation = PreferencesDialog.DURATION_REPRESENTATIONS[duration_index]
        self.ui.label_duration_representation.setText(duration_representation)

        language_index = utils.preferences.value("language_representation").toInt()[0]
        language_representation = PreferencesDialog.LANGUAGE_REPRESENTATIONS[language_index]
        self.ui.label_language_representation.setText(language_representation)

        separator_index = utils.preferences.value("words_separator").toInt()[0]
        separator_representation = PreferencesDialog.WORDS_SEPARATORS_REPRESENTATIONS[separator_index]
        self.ui.label_separator_representation.setText(separator_representation)

    def update_example_movie(self, renaming_rule):
        # generate new name for example movie
        example_movie_new_name = self.example_movie.generate_new_name(renaming_rule)
        # show it on label
        self.ui.label_example_movie_name.setText(example_movie_new_name)

    def rule_changed(self, parent = None, start = None, end = None):
        """
        called when renaming rule changes
        
        creates and saves new renaming rule, and generate the movie example's new name
        """

        rule = []
        for index in range(self.ui.list_visual_rule.count()):
            text = self.ui.list_visual_rule.item(index).text()
            # when an item is moved inside the list_visual_rule, firstly 
            # a new empty item is inserted into the destination location, then 
            # the item from source location is deleted. that function is called 
            # for both events (insertion and deletion), and when is called for
            # the insertion event after a list items move, the list contains an empty item,
            # which is a kind of error. 
            if text != '':
                rule.append(self.VISUAL_TO_RENAMING_RULE[text])
        # creates renaming rule
        renaming_rule = '.'.join(rule)
        #save renaming rule on settings
        utils.preferences.setValue("renaming_rule", renaming_rule)
        #update example movie
        self.update_example_movie(renaming_rule)

    def remove_rule(self):
        """
        removes selected rule
        """

        # get selected items in rule
        selected_items = self.ui.list_visual_rule.selectedItems()
        # remove its from list
        for item in reversed(selected_items):
            row = self.ui.list_visual_rule.row(item)
            self.ui.list_visual_rule.takeItem(row)

    def clean_rule(self):
        """
        cleans rule (remove all renaming rules)
        """

        self.ui.list_visual_rule.clear()
        # needs to call rule_changed because clear() doesn't 
        # throw any signal
        self.rule_changed()

    def add_title(self):
        """
        add title to rule
        """

        self.ui.list_visual_rule.addItem(self.TITLE)

    def add_original_title(self):
        """
        add aka to rule
        """

        self.ui.list_visual_rule.addItem(self.ORIGINAL_TITLE)

    def add_year(self):
        """
        add year to rule
        """

        self.ui.list_visual_rule.addItem(self.YEAR)

    def add_director(self):
        """
        add director to rule
        """

        self.ui.list_visual_rule.addItem(self.DIRECTOR)

    def add_duration(self):
        """
        add runtime to rule
        """

        self.ui.list_visual_rule.addItem(self.DURATION)

    def add_language(self):
        """
        add language to rule
        """

        self.ui.list_visual_rule.addItem(self.LANGUAGE)

    def add_round_brackets(self):
        """
        add opened and closed round brackets to rule
        """

        self.ui.list_visual_rule.addItem(self.OPENED_ROUND_BRACKET)
        self.ui.list_visual_rule.addItem(self.CLOSED_ROUND_BRACKET)

    def add_square_brackets(self):
        """
        add opened and closed square brackets to rule
        """

        self.ui.list_visual_rule.addItem(self.OPENED_SQUARE_BRACKET)
        self.ui.list_visual_rule.addItem(self.CLOSED_SQUARE_BRACKET)

    def add_curly_brackets(self):
        """
        add opened and closed curly brackets to rule
        """

        self.ui.list_visual_rule.addItem(self.OPENED_CURLY_BRACKET)
        self.ui.list_visual_rule.addItem(self.CLOSED_CURLY_BRACKET)

    def show_preferences(self):
        self.ui.preferences_dialog.exec_()
        renaming_rule = utils.preferences.value("renaming_rule").toString()
        self.update_representations()
        # update example movie
        self.update_example_movie(renaming_rule)

    def close(self):
        send_usage_statistics()
        self.accept()