from wxPython.wx import *
import sys

# Find the installation dir of snarfzilla
if sys.path[0] == "":
    snarfdir = "."
else:
    snarfdir = sys.path[0]

class panelcreate(wxPanel):
    def __init__(self,parent):
        wxPanel.__init__(self, parent, -1)
        self.SetAutoLayout(true)

        # Ok, so maybe this was my first window and I didn't know about wxSizers...
        row = 25
        col = 90
        width = 225

        #self.rembutID=NewId()
        self.rembut = wxButton(self, 1500, "Select MP3    ", wxPoint(330, row))
        self.id3but = wxButton(self, 1501, "Write ID3 Tags", wxPoint(330, row+30))
        self.id3msg = wxStaticText(self, -1, "", wxPoint(430, 55), wxSize(75, 20))
        self.addbut = wxButton(self, 1502, "Add to Catalog", wxPoint(330, row+60))
        self.fairtunesbut = wxButton(self, 1504, "Fairtunes", wxPoint(330, row+90))

        EVT_BUTTON(self, 1500, self.fileSelect)
        EVT_BUTTON(self, 1501, self.writeID3)
        EVT_BUTTON(self, 1502, self.addCatalog)
        EVT_BUTTON(self, 1504, self.fairtunes)
        wxStaticText(self, -1, "WARNING: ", wxPoint(400, row + 200), wxSize(100, 20))
        wxStaticText(self, -1, "Don't use this screen.Waiting for Espra to", wxPoint(400, row + 230), wxSize(230, 20))
        wxStaticText(self, -1, "get off their butt and publish a catalog spec.", wxPoint(400, row + 260), wxSize(250, 20))
        wxStaticText(self, -1, "Filename", wxPoint(5, row), wxSize(75, 20))
        self.inpFilename = wxTextCtrl(self, 5, "", wxPoint(col, row), wxSize(width, 20))
        self.inpFilename.SetInsertionPoint(0)

        wxStaticText(self, -1, "Artist", wxPoint(5, row+30), wxSize(75, 20))
        self.inpArtist = wxTextCtrl(self, 10, "", wxPoint(col, row+30), wxSize(width, 20))
        self.inpArtist.SetInsertionPoint(0)

        wxStaticText(self, -1, "Song Title", wxPoint(5, row+60), wxSize(75, 20))
        self.inpTitle = wxTextCtrl(self, 20, "", wxPoint(col, row+60), wxSize(width, 20))
        self.inpTitle.SetInsertionPoint(0)

        wxStaticText(self, -1, "Album", wxPoint(5, row+90), wxSize(75, 20))
        self.inpAlbum = wxTextCtrl(self, 30, "", wxPoint(col, row+90), wxSize(width, 20))
        self.inpAlbum.SetInsertionPoint(0)

        wxStaticText(self, -1, "Comment", wxPoint(5, row+120), wxSize(75, 20))
        self.inpComment = wxTextCtrl(self, 40, "", wxPoint(col, row+120), wxSize(width, 20))
        self.inpComment.SetInsertionPoint(0)

        wxStaticText(self, -1, "Genre", wxPoint(5, row+150), wxSize(75, 20))
        self.inpGenre = wxTextCtrl(self, 50, "", wxPoint(col, row+150), wxSize(width, 20))
        self.inpGenre.SetInsertionPoint(0)

        wxStaticText(self, -1, "Year", wxPoint(5, row+180), wxSize(75, 20))
        self.inpYear = wxTextCtrl(self, 60, "", wxPoint(col, row+180), wxSize(width, 20))
        self.inpYear.SetInsertionPoint(0)

        self.header = wxStaticText(self, -1, "", wxPoint(col, row+210), wxSize(width, 20))
        self.insbut = wxButton(self, 1505, "Upload Catalog to Freenet", wxPoint(90, row+250))
        EVT_BUTTON(self, 1505, self.insCatalog)

        wxStaticText(self, -1, "Catalog Name", wxPoint(5, row+280), wxSize(80, 20))
        self.inpCatalogName = wxTextCtrl(self, 90, "", wxPoint(col, row+280), wxSize(width, 20))
        self.inpCatalogName.SetInsertionPoint(0)

        self.catListID=wxNewId()
        self.catList = wxListCtrl(self, self.catListID, wxPoint(10,330), wxDefaultSize,wxLC_REPORT|wxSUNKEN_BORDER)
        lc = wxLayoutConstraints()
        lc.top.SameAs(self, wxTop, 330)
        lc.left.SameAs(self, wxLeft, 10)
        lc.bottom.SameAs(self, wxBottom, 10)
        lc.right.SameAs(self, wxRight, 10)

        self.catList.SetConstraints(lc)
        self.catList.InsertColumn(0, "Artist")
        self.catList.InsertColumn(1, "Title")
        self.catList.InsertColumn(2, "Album")
        self.catList.InsertColumn(3, "Time")
        self.catList.InsertColumn(4, "Bitrate")
        #self.catList.SetColumnWidth(0, wxLIST_AUTOSIZE_USEHEADER)
        self.catList.SetColumnWidth(0, 170)
        self.catList.SetColumnWidth(1, 170)
        self.catList.SetColumnWidth(2, 170)
        self.catList.SetColumnWidth(3, wxLIST_AUTOSIZE_USEHEADER)
        self.catList.SetColumnWidth(4, wxLIST_AUTOSIZE_USEHEADER)
        self.playlist = {}

    def insCatalog(self, event):
        xit = Xml.XML_document()
        xit.catalog()
        items = self.playlist.items()
        for x in range(len(items)):
            key, data = items[x]
            xit.song()
            xit.artist(data[0])
            xit.title(data[1])
            xit.album(data[2])
            xit.time(data[3])
            xit.filesize(data[4])
            xit.bitrate(data[5])
            xit.freq(data[6])
            xit.genre(data[7])
            xit.year(data[8])
            xit.key("freeent:KSK@blah")
        f = self.inpCatalogName.GetValue()
        if f == "":
            filename = "Enter_a_catalog_name_next_time.xml"
        else:
            filename = f + ".xml"

        xit._output(filename)
        self.inpFilename.SetValue("")
        self.inpArtist.SetValue("")
        self.inpTitle.SetValue("")
        self.inpAlbum.SetValue("")
        self.inpComment.SetValue("")
        self.inpGenre.SetValue("")
        self.inpYear.SetValue("")
        self.playlist = {}
        self.id3msg.SetLabel("")
        self.header.SetLabel("")
        self.catList.ClearAll()

    def addCatalog(self, event):
        x = len(self.playlist.items())

        artist = self.inpArtist.GetValue()
        title = self.inpTitle.GetValue()
        album = self.inpAlbum.GetValue()
        comment = self.inpComment.GetValue()
        genre = self.inpGenre.GetValue()
        year = self.inpYear.GetValue()
        version = self.i['VERSION']
        layer = self.i['LAYER']
        bitrate = self.i['BITRATE']
        frequency = self.i['FREQUENCY']
        sec = ("%s" % self.i['SS'])
        if len(sec) == 1:    # Add leading zero if seconds < 10 so time looks pretty (4:04 instead of 4:4)
            seconds = ("0%s" % sec)
        else:
            seconds = ("%s" % sec)
        length = "%s:%s" % (self.i['MM'], seconds)

        self.playlist[x+1] = ( artist, title, album, comment, genre, year, version, layer, bitrate, frequency, length )
        self.catList.InsertStringItem(x, artist)
        self.catList.SetStringItem(x, 1, title)
        self.catList.SetStringItem(x, 2, album)
        self.catList.SetStringItem(x, 3, length)
        self.catList.SetStringItem(x, 4, "%s Kbps" % (bitrate))
        self.catList.SetItemData(x, x)

    def writeID3(self, event):
        filename = self.inpFilename.GetValue()
        if filename != "":
            artist = string.rstrip(self.inpArtist.GetValue())
            title = string.rstrip(self.inpTitle.GetValue())
            album = string.rstrip(self.inpAlbum.GetValue())
            comment = string.rstrip(self.inpComment.GetValue())
            genre = string.rstrip(self.inpGenre.GetValue())
            year = string.rstrip(self.inpYear.GetValue())
            tag=ID3Tag(filename)
            tag.Title(title)
            tag.Artist(artist)
            tag.Album(album)
            tag.Year(year)
            tag.Genre(genre)
            tag.Comment(comment)

            tag.Commit()
            self.id3msg.SetLabel("Tags written")
        else:
            self.id3msg.SetLabel("You need a filename.")


    def fileSelect(self, event):
        dlg = wxFileDialog(self, "Choose a file", ".", "", "*.mp3", wxOPEN|wxMULTIPLE)
        if dlg.ShowModal() == wxID_OK:
            for path in dlg.GetPaths():
                self.inpFilename.SetValue(path)
                dlg.Destroy()
        self.id3msg.SetLabel("")
        #MP3 header info:
        self.i = mp3info(path)
        self.header.SetLabel('MPEG%d, L%d %dKbps %dHz Stereo' % \
                              (self.i['VERSION'], self.i['LAYER'], self.i['BITRATE'], self.i['FREQUENCY']))

        ### i['STEREO'] # Not implemented, I faked it
        ### i['MODE'] # Not implemented
        ### i['COPYRIGHT'] # Not implemented

        wxStaticText(self, -1, "              ", wxPoint(430, 55), wxSize(75, 20)) # Ummm this is cheesier than Velveeta.

        # ID3 v1 info:
        try:
            tag = ID3Tag(path)
            tag.Read()
            self.inpArtist.SetValue(string.rstrip(tag.theArtist()))
            self.inpTitle.SetValue(string.rstrip(tag.theTitle()))
            self.inpAlbum.SetValue(string.rstrip(tag.theAlbum()))
            self.inpComment.SetValue(string.rstrip(tag.theComment()))
            self.inpGenre.SetValue(string.rstrip(tag.theGenre()))
            self.inpYear.SetValue(string.rstrip(tag.theYear()))
        except:
            self.inpArtist.SetValue("")
            self.inpTitle.SetValue("")
            self.inpAlbum.SetValue("")
            self.inpComment.SetValue("")
            self.inpGenre.SetValue("")
            self.inpYear.SetValue("")

    def fairtunes(self, event):
        artist = self.inpArtist.GetValue()
        nice_artist = string.joinfields(string.splitfields(artist,' '),'%20') # Fix this: theres some url pretty deal in Python?
        #print nice_artist
        # Added client=snarfzilla per Matt Goyer at Fairtunes
        url = 'http://www.fairtunes.com/bare_search.jsp?searchTerms=' + nice_artist + '&action=dosearch&client=snarfzilla'
        #print url
        doit = browserloc + " '" + url + "' &"
        os.system(doit)

