require 'musicbrainz'
require 'discogs'
require 'nokogiri'
require 'zlib'

class ImportController < ApplicationController
  def self.importArtist name, dry_run = false
    artist = Artist.find_or_create_by_name(name)
    return 3 if artist.status == 1
    
    begin
      lastfm_artist = LastFM::Artist.get_info( artist: name )
      unless artist.mbid.nil? or artist.mbid.empty?
        brainz_artist = MusicBrainz::Artist.find(artist.mbid)
      else
        brainz_artist = MusicBrainz::Artist.find_by_name(name)
      end
    rescue => e
      lastfm_artist = { 'artist' => {
        'bio' => { 'summary' => '' },
        'image' => [ nil, nil, nil, { '#text' => '' } ],
        'stats' => { 'listeners' => 0 }
      } }
      ap e.message
      ap e.backtrace
    end
    
    if brainz_artist.nil?
      artist.mbid = nil
      artist.status = 2
      artist.save
      return 2
    end

    begin
      # Save artist
      artist.desc = lastfm_artist['artist']['bio']['summary']
      artist.pic_url = lastfm_artist['artist']['image'][3]['#text']
      artist.listeners = lastfm_artist['artist']['stats']['listeners']
      artist.artist_type = brainz_artist.type
      artist.mbid = brainz_artist.id
      artist.save
      
      brainz_artist.urls.each do |service, url|
        ArtistLink.new(
          artist_id: artist.id,
          service: service.to_s,
          url: url
        ).save
      end
      
      unless brainz_artist.urls[:discogs].nil?
        Discogs.get_master_albums(brainz_artist.urls[:discogs]).each do |info|
          begin
            puts "  * "+info[:title]+" ("+info[:year]+") -- http://api.discogs.com/"+info[:uri]+")"
            stream = open("http://api.discogs.com/"+info[:uri]+"?f=xml",
              'User-Agent' => 'Haven Import Bot',
              'Accept-Encoding' => 'gzip, deflate'
            )
            if (stream.content_encoding.empty?)
              body = stream.read
            else
              body = Zlib::GzipReader.new(stream).read
            end
            # Creating album
            album = Album.new(
              name: info[:title],
              artist_id: artist.id,
              year: info[:year],
              status: 1,
              master: true
            )
            begin
              album_lastfm = LastFM::Album.get_info( artist: lastfm_artist['artist']['name'], album: info[:title] )
              album_image = album_lastfm['album']['image'][3]['#text']
            rescue
              album_image = ''
            end
            album.pic_url = album_image
            album.has_pic = (album_image != '' and not album_image.nil?)
            album.save
            Discogs.save_album(artist, album, Nokogiri::HTML(body))
          end
          sleep 1
        end
      end
      
      artist.status = 1
    rescue => e
      ap e.message
      ap e.backtrace
      artist.status = 2
    end
    
    artist.save unless dry_run
    artist.status
  end
  
  def self.parseLastfmXML path
    Nokogiri::XML(open(path)).css('lfm > artists > artist').map do |node|
      artist = {}
      artist[:name] = node.css('name').text
      artist[:mbid] = nil
      artist[:mbid] = node.css('mbid').text unless node.css('mbid').empty?
      artist
    end
  end
  
end