# -*- coding: utf-8 -*-

#   This file is part of emesene.
#
#    Emesene is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    emesene is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with emesene; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  021self.maxMessageNumber-1301  USA

VERSION = '0.1'
import Plugin

class MainClass( Plugin.Plugin ):
    '''Main plugin class
    This pluging suppose that in pm0 is stored tha last used message and in the others pm$i the other message like a LRU (Least Recenty Used) List'''

    description = _('Save many personal message between sessions and reset them.')
    authors = { 'Iacopo Masi' : 'iacopo.masi at gmail dot com' }
    website = 'http://www.iacopomasi.net'
    displayName = _('Personal Message')
    name = 'PersonalMessage'
    def __init__( self, controller, msn ):
        '''Contructor'''

        Plugin.Plugin.__init__( self, controller, msn )

        self.description = _('Save many personal message between sessions and reset them.')
        self.authors = { 'Iacopo Masi' : 'iacopo.masi at gmail dot com' }
        self.website = 'http://www.iacopomasi.net'
        self.displayName = _('Personal Message')
        self.name = 'PersonalMessage'

        self.controller = controller
        self.config = controller.config
        self.config.readPluginConfig(self.name)

        self.enabled = False
        self.maxMessageNumber=int(self.config.getPluginValue(self.name, 'maxM', '10'))

    def start( self ):
        '''start the plugin'''
        self.enabled = True
        self.maxMessageNumber=int(self.config.getPluginValue(self.name, 'maxM', '10'))
        self.msn.changePersonalMessage(self.config.getPluginValue(self.name, 'pm0', ''))
        self.msn.connect( 'self-personal-message-changed', self.action )

    def stop( self ):    
        '''stop the plugin'''
        
        self.enabled = False
        
    def action( self, msnp, user, pm ):
        if self.enabled:
            self.doRemember(pm)

        
    def check(self):
        return (True, 'Ok')

    def configure(self):
        '''configure the plugin'''
        
        guiOptions = []
        pmList=[]
        
        #Storing messages for GUI options
        for i in range(self.maxMessageNumber):
            if self.config.getPluginValue(self.name, 'pm'+ str(i), '') == '':
                pmList.append(  "No Message" )
            else:
                pmList.append(  self.config.getPluginValue(self.name, 'pm'+ str(i), '') )
        
        #GUI Building
        guiOptions.append( Plugin.Option( 'PastMessage', list, _('Select a message'), \
        _('Permit to select some past message'), self.config.getPluginValue(self.name, 'pm0', '')  , pmList))

        guiOptions.append( Plugin.Option( 'maxNumber', str, _('Message to remember'), _('Max message to remember'), self.maxMessageNumber) )
        guiOptions.append(Plugin.Option( 'Reset', bool, _('Reset the Message History'), _('Reset the Message History'), False) )
        
        #To import the message from previous plugin
        #guiOptions.append(Plugin.Option( 'Import', bool, 'Import Message from previous Personal Message Plugin', 'Import Message from other Plugin', False) )
        result = Plugin.ConfigWindow(_('Personal Message v2'), guiOptions).run()


        #Parsing User option selected
        if result <> None:
            #User sets a new Message to use...
            if result.has_key( 'PastMessage' ):
                message = result[ 'PastMessage' ].value
                #..but he does not select anything
                if message <> 'No Message':
                    self.doRemember(message)
                    self.msn.changePersonalMessage(self.config.getPluginValue(self.name, 'pm0', ''))
            
            #User resets alla msg
            if result.has_key( 'Reset' ):
                if result[ 'Reset' ].value == True:
                    self.doRemember("",True)
                    self.msn.changePersonalMessage(self.config.getPluginValue(self.name, 'pm0', ''))
            
            #User change the maximum message to remember
            if result.has_key('maxNumber'):
                    self.maxMessageNumber = int(result[ 'maxNumber' ].value)
                    self.config.setPluginValue( self.name, 'maxM', self.maxMessageNumber )

#To import the message from previous plugin
#            if result.has_key('Import'):
#                if result[ 'Import' ].value == True:
#                    pmPlugin = self.controller.pluginManager.getPlugin("PersonalMessage")
#                    if not pmPlugin or not pmPlugin.enabled:
#                        if self.controller.pluginManager.startPlugin("PersonalMessage"):
#                            self.doRemember(self.config.getPluginValue("PersonalMessage", 'pm', ''))    
#                            self.msn.changePersonalMessage(self.config.getPluginValue(self.name, 'pm0', ''))
#                            self.controller.pluginManager.stopPlugin("PersonalMessage")
#                        else:
#                            print "Personal Message Plugin not activable"
#                    else:
#                        self.doRemember(self.config.getPluginValue("PersonalMessage", 'pm', ''))    
#                        self.msn.changePersonalMessage(self.config.getPluginValue(self.name, 'pm0', ''))


    def doRemember(self,pm,reset=False):
            '''The main Function of the plugin. It take the pm to store as the message to use in position zero
             and update the LRU list in the file configuration. The second (false as default) is used to make the reset, if true.'''
            
            #Insertion and Updating code
            if (not reset):
                pmList= [pm]
                #i=0
                for i in range(self.maxMessageNumber):
                    if  pmList[0] <> self.config.getPluginValue(self.name, 'pm'+ str(i), ''):
                        pmList.append(  self.config.getPluginValue(self.name, 'pm'+ str(i), '') )

                for i in range(len(pmList) -1):
                    print len(pmList)
                    self.config.setPluginValue(self.name, 'pm'+str(i), pmList[i])
                    print i
            
            #Reseting code
            else:
                for i in range(self.maxMessageNumber):
                    self.config.setPluginValue(self.name, 'pm'+str(i), "")
