 #
 # This file is part of the Anotatornia suite.
 # 
 # Copyright © 2007, 2008, 2009, 2010 by Instytut Podstaw Informatyki
 # Polskiej Akademii Nauk (IPI PAN; Institute of Computer Science, Polish
 # Academy of Sciences; cf. www.ipipan.waw.pl).  All rights reserved.
 # 
 # This file may be distributed and/or modified under the terms of the
 # GNU General Public License version 3 as published by the Free Software
 # Foundation and appearing in the file COPYING included in the packaging
 # of this file.  (See http://www.gnu.org/licenses/translations.html for
 # unofficial translations.)
 # 
 # A commercial license is available from IPI PAN (contact
 # Michal.Ciesiolka.waw.pl or ipi.waw.pl for more
 # information).  Licensees holding a valid commercial license from IPI
 # PAN may use this file in accordance with that license.
 # 
 # This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
 # THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 # PURPOSE.
 #


require 'jcode'

## require 'connection_pool'


module MigrationHelper
  # metody tego modułu zwracają #true jeśli coś zrobią lub #{false}, jeśli okażą się no\dy opem.


  def addcolumn( tablename, colname, colspec )
    unless tablename.to_s.camelize.constantize.column_names.include?( colname.to_s )
      execute "alter table #{tablename} add column #{colname}  #{colspec}"
      return true
    else return false
    end
  end # of #{addcolumn}


  def addindex( tablename, columns, unique=nil )
    dtname = tablename.to_s.split('.')
    tname = dtname.delete_at( -1 )
    dbname_dot = if dtname[0]
               dtname[0] + '.'
             end

    cols = [ columns ].flatten
    indexname = ([tname] + cols).join('_')
    if     ActiveRecord::Base.find_by_sql( "pragma index_info( #{indexname} )")[0]
      return false
    else
      execute " create #{if unique : 'unique ' end}index if not exists " +
        " #{dbname_dot}#{indexname} on #{tname}( #{cols.join(', ')});"
      return true
    end
  end # of #{addindex}


  def dropindex( indexname )
    if     ActiveRecord::Base.find_by_sql( "pragma index_info( #{indexname} )")[0]
      execute " drop index if exists #{indexname}; "
      return true
    else return false
    end
  end


  def droptable( tablename, force=nil )
    if tables.include?( "#{tablename}" ) or force # uwaga! tu jest zwykłe #{include?}, które odróżnia symbol od stringa, dlatego wziąłem w~cudzysłów
      execute " drop table if exists #{tablename}; "
      return true
    else return false
    end
  end


  def przepisz_tabelę( tabledef, *indices )
    tabledef =~  /^[^(]* (?:(\w+)\.)*(\w+) *\(/
    dbname = $1
    tname = $2
    dtname = [$1, $2].compact.join('.')

    oldcols =  tname.camelize.constantize.column_names
        
    puts tname.inspect
    
    columns = []
    tabledef.gsub( /(?:\(|,|--.*\n)\s*(\w+)/ ) { |match| # [database-name.]table-name
      columns << $1      
    }

    puts columns.inspect
    
    columns &= oldcols
    coljoin = columns.join(', ')
    puts coljoin

    execute " alter table #{dtname} rename to #{tname}_old;"
    execute tabledef
    execute " insert into #{dtname} (#{coljoin}) 
select #{coljoin} from #{tname}_old "

    droptable tname + "_old", :force
    droptable dtname + "_old", :force

    indices.each{ |ind|
      if ind.kind_of?( String ) and ind =~ /\bcreate\b.*\bindex\b/i
        execute ind
      else
        cols, unique = ind
        addindex( dtname, cols, unique )
      end
    }
  end # of #przepisz_tabelę

  
  def pragmas_for_update
    execute " pragma locking_mode = exclusive; "  
    execute " pragma synchronous=off; "
  end

  def pragmas_normal
    execute " pragma locking_mode = normal; "  
    execute " pragma synchronous=normal; "
  end


  unless defined?( $anotatorniæ_killed )  
    $anotatorniæ_killed = false
  end


  def kill_anotatorniæ_if_8003
    if AnoVersion.port == 8003
      unless     $anotatorniæ_killed 
        `killall anotatornia-keeprunning`
        `./anotatornia-mongrels stop`
        `tar -cjvf bazy-bk-\`date +%F-%H%M\`.tar.bz2 anotatornia_8003.db uzytkownicy_8003.db` unless UNatrora.x
        $anotatorniæ_killed = true
      end
    end
  end

  def kill_anotatorniæ_if_8003_nobackup
    if AnoVersion.port == 8003
      unless     $anotatorniæ_killed 
        `killall anotatornia-keeprunning`
        `./anotatornia-mongrels stop`
      end
    end
  end

end # of module



class Uzytkownicy8003 < ActiveRecord::Base
  self.abstract_class = true
  establish_connection(
                       ## establish_connection (ActiveRecord::ConnectionAdapters::ConnectionHandler)
                       ## connection( ActiveRecord::Base.establish_connection( 
                       :adapter => "sqlite3",
                       :database => "uzytkownicy_8003.db" )
end
