#!/usr/bin/python
# -*- coding: iso-8859-2 -*-
# Made by Zamber ( http://zamber.net/ )
# Podoba się? Postaw mi piwko :D

import ekg
import os
import time
# import random
# import linecache
# do quote

adm  = [5299372] # lista numerow uprzywilejowanych (dodawanie treści)
uadm = [5299372] # uber admin! (blokowanie, wysyłanie wiad.)

# trzeba uzupelnic ;/
opis = "Wyświetlanie zmian dla klasy (wpisz np. 3e)"

admhelp = "BronxBot v1.2 coded by Zamber ( http://zamber.net/ )\nDostępne komendy dla administratora: 'adm pomoc', 'adm opis', 'adm zmiany', 'adm mm'.\n'adm help' - wyświetla tą wiadomość.\n'adm opis' - pozwala ustawić opis bota.\n'adm zmiany' - pozwala ustawić tekst dla zmian.\n'adm news' - pozwala ustawić tekst dla newsów.\n'adm mm' - wysyła masową wiadomość do zapisanych na liście."

helpshort = "\nNapisz 'pomoc' aby dowiedzieć się więcej ;)."
masshelp  = "\nNie chcesz dostawać automatycznych powiadomień? Napisz do mnie 'usun'."

lista = "/home/zamber/Desktop/bronxbot/lista.txt"
log   = "/home/zamber/Desktop/bronxbot/log.txt"
# quotes = "/home/zamber/Desktop/bronxbot/quotes.txt"

def isint(n): # sprawdza czy n jest typu int
  try:
    dummy = int(n)
    return 1
  except ValueError:
    return 0

def check(list, text): # sprawdza wyst. textu w liście
  for word in list:
    if str(word) in str(text) :
      return 1
  return 0

def buff(): # wiem, że nieładnie ale handle_msg przekazuje zmienną time i się mieszało :P
  time.sleep(1)
  return

# obsługa plików tekstowych

#def quote():
#  if quotes != '':
#    quote = linecache.getline(quotes, random.randint(1,561))
#  return quote

def save(file, text, act): # obs. zapisywania plików
  if file != "":
    if act == "a":
      f = open(file, "a")
    elif act == "w":
      f = open(file, "w")
    else:
      return ekg.command("/msg %d szukaj błędu padawanie!" % (adm) )
    f.write(text)
    f.close()
  return "Zapisano: " + text

def read(file, beg=''): # obs. czytania plików
  text = ""
  if file != '':
    f = open(file, 'r')
    if beg == '' :
      for line in f:
        text = text + line
    else:
      for line in f:
        if line[0:2] == beg : # czytanie pojedyńczej klasy
         text = text + line
    f.close()
    if text == '' :
      return "Brak zmian dla tej klasy."
  return text

def list(file, uin, act, msg=""): # obs. listy kontaktów
  if file != '':
    list = []
    f = open(file, "r")
    for line in f:
      list.append(line)
    f.close()

    if act == 'send' and msg != '' : # obs. wysyłania wiad. masowych
      count = 0
      for item in list :
        if isint(item) == 1:
          count += 1
          ekg.command("/msg %d %s" % (int(item), msg) )
          buff()
      return "Wiadomość \n\n%s\n\n została wysłana do %d użytkowników." % (msg, count)
    elif act == 'add' : # dodawanie do listy
      for item in list :
        if str(uin) in item :
          return 0
      save(file, str(uin) + "\n", "a")
      return 1
    elif act == 'del' : # kasowanie z listy
      for item in list :
        if str(uin) in item :
          list.remove(item)
          save(file, "", "w")
          for item in list :
            save(file, str(item), "a")
          return 1
      return 0
    else:
      return "Wpisz treść wiadomości!"
  else:
    return "szukaj błędu padawanie!"

# / obsługa plików tekstowych

# info globals text
help_txt         = "/home/zamber/Desktop/bronxbot/pomoc.txt"
news_txt         = "/home/zamber/Desktop/bronxbot/news.txt"
zmiany_txt       = "/home/zamber/Desktop/bronxbot/zmiany.txt"
zmiany_short_txt = "/home/zamber/Desktop/bronxbot/zmiany_short.txt"

# info globals
zmiany_short = read(zmiany_short_txt)
zmiany       = read(zmiany_txt)
help         = read(help_txt)
news         = read(news_txt)

def reloadtxt():
  global help, news, zmiany, zmiany_short
  zmiany_short = read(zmiany_short_txt)
  zmiany       = read(zmiany_txt)
  help         = read(help_txt)
  news         = read(news_txt)

# antyspam globals
lasttext = ""
lastuin = 0
spamcount = 0

def spam(pres, last, count): # antyspam count
  if pres == last :
    count += 1
  else:
    count = 0
  return count

def init(): # init skryptu
  ekg.printf("generic", "Bot on!")
  ekg.command("back %s %s" % (zmiany_short, opis) )
  return 1

def deinit(): # deinit skryptu
  ekg.printf("generic", "Bot off...")

# jazda!

def handle_msg(uin, name, msgclass, text, time, secure):

  global msgact
  if msgclass == 4 :
    msgact = "msg"
  else:
    msgact = "query"

# antyspam

  global lasttext
  global lastuin
  global spamcount

  prestext  = str(uin) + text
  spamcount = spam(prestext, lasttext, spamcount)
  lasttext  = prestext
  lastuin   = uin

  if spamcount == 1 and lastuin == uin :
    ekg.command("msg %d Jeżeli wyślesz ponownie ten sam tekst zostaniesz zablokowany (antyspam)!" % (uin) )
    return
  elif spamcount == 2 and lastuin == uin :
    ekg.command("msg %d Zostałeś zablokowany!\nJeżeli chcesz by twój numer został odblokowany napisz do admina (5299372)." % (uin) )
    ekg.command("ignore %d *" % (uin) )
    ekg.command("block %d" % (uin) )
    return
  elif spamcount >= 3 and lastuin == uin :
    return
  else:
    spamcount = 0
# / antyspam

  texto = text # zachowanie tekstu z dużymi literami
  text = text.lower()

  buff() # czeka sekundkę by nie przekroczyć limitu 100 wiadomości na minutę

  if len(text) == 0 or text[0:4] == "help" or text[0:5] == "pomoc" or text[0:4] == "info" or text[0:1] == "?" : # wyświetla pomoc
    ekg.command("%s %d %s" % (msgact, uin, help) )
    return
  elif text[0:5] == "dodaj" : # dodaje kontakt do listy
    if list(lista, uin, "add") == 1 :
      ekg.command("add %d %d" % (uin, uin) )
      ekg.command("%s %d OK: Dodano nr. %d do listy powiadamianych.\nAby się wypisać napisz 'usun'." % (msgact, uin, uin) )
      return
    else:
      ekg.command("%s %d ERROR: Numer %d jest już dodany do listy powiadamianych." % (msgact, uin, uin) )
      return
  elif text[0:4] == "usun" or text[0:4] == "usuń" : # usuwa kontakt z listy
    if list(lista, uin, "del") == 1 :
      ekg.command("%s %d OK: Numer %d został usunięty z listy powiadamianych." % (msgact, uin, uin) )
      return
    else:
      ekg.command("%s %d ERROR: Numer %d nie jest zapisany na liście powiadamianych." % (msgact, uin, uin) )
      return
  elif isint(text[0:1]) == 1 and isint(text[1:2]) == 0 and len(text) >= 2 :
    ekg.command("%s %d Kl: godz - info\n%s" % (msgact, uin, read(zmiany_txt, text[0:2])) )
    return
  elif text[0:6] == "zmiany" : # wyświetla zmiany
    ekg.command("%s %d %s %s" % (msgact, uin, zmiany, helpshort) )
    return
  elif text[0:4] == "news" : # wyświetla newsy
    ekg.command("%s %d %s %s %s" % (msgact, uin, news, "\nChcesz ogłosić coś ważnego? Napisz do admina (poprzedzając wiadomość wykrzyknikiem).", helpshort) )
    return
  elif text[0:7] == "dzwonki" : # wyświetla dzwonki
    ekg.command("%s %d 1: 8:00 - 8:45 \n2: 8:50 - 9:35 \n3: 9:45 - 10:30 \n4: 10:45 - 11:30 \n5: 11:40 - 12:25 \n6: 12:35 - 13:20 \n7: 13:35 - 14:20\n8: 14:25 - 15:10\n9: 15:15 - 16:00" % (msgact, uin) )
    return
  elif text[0:1] == "!" : # wysyła wiadomość do admina i zapisuje ją w logu
    ekg.command("msg %d %d : %s " % (uadm[0], uin, texto) )
    savetext = str(uin) + " : " + texto[1:] + "\n"
    save(log, str(savetext), "a")
    return
  elif check(adm, uin) == 1 : # stuff dla obu grup adminów
    if text[0:9] == "adm pomoc" : # pomoc dla admina
      ekg.command("%s %d %s" % (msgact, uin, admhelp) )
      return
    if text[0:8] == "adm opis" : # ustawianie opisu bota
      ekg.command("back %s %s" % (zmiany_short, texto[9:]) )
      savetext = "adm " + str(uin) + " : " + texto + "\n"
      save(log, str(savetext), "a")
      ekg.command("%s %d Opis został ustawiony." % (msgact, uin) )
      return
    elif text[0:8] == "adm news" : # ustawianie newsów
      ekg.command("%s %d %s" % (msgact, uin, save(news_txt, texto[9:], "w")) )
      savetext = "adm " + str(uin) + " : " + texto + "\n"
      save(log, str(savetext), "a")
      ekg.command("%s %d Newsy zostały zapisane." % (msgact, uin) )
      return
    elif text[0:10] == "adm zmiany" : # ustawianie zmian
      ekg.command("%s %d %s" % (msgact, uin, save(zmiany_txt, texto[11:], "w")) )
      savetext = "adm " + str(uin) + " : " + texto + "\n"
      save(log, str(savetext), "a")
      ekg.command("%s %d Zmiany zostały zapisane." % (msgact, uin) )
      return
    elif text[0:11] == "adm zmianys" : # ustawianie krótkich zmian
      ekg.command("%s %d %s" % (msgact, uin, save(zmiany_short_txt, texto[12:], "w")) )
      savetext = "adm " + str(uin) + " : " + texto + "\n"
      save(log, str(savetext), "a")
      ekg.command("%s %d Krótkie zmiany zostały zapisane." % (msgact, uin) )
      return
    elif text[0:6] == "adm mm" : # wysyłanie masowych wiad.
      ekg.command("%s %d %s" % (msgact, uin, list(lista, 0, "send", texto[7:])) )
      savetext = "adm " + str(uin) + " : " + texto + "\n"
      save(log, str(savetext), "a")
      return
    elif text[0:10] == "adm reload" : # ładowanie plików tekstowych od nowa
      reloadtxt()
      ekg.command("%s %d Pliki zostały załadowane ponownie." % (msgact, uin) )
      return
    else: # stuff dla uber admina ;)
      if check(uadm, uin) == 1 :
        if text[0:9] == "adm block" : # blokowanie
          ekg.command("block %s" % (texto[10:]) )
          ekg.command("ignore %s *" % (texto[10:]) )
          ekg.command("%s %d Numer %s został zablokowany." % (msgact, uin, texto[10:]) )
          return
        elif text[0:11] == "adm unblock" : # odblokowywanie
          ekg.command("unblock %s" % (texto[12:]) )
          ekg.command("unignore %s" % (texto[12:]) )
          ekg.command("%s %d Numer %s został odblokowany." % (msgact, uin, texto[12:]) )
          return
        elif text[0:7] == "adm msg" : # wysyłanie bezpośrednich wiadomości
          ekg.command("msg %s" % (texto[8:]) )
          return
    ekg.command("%s %d '%s' - zła komenda.\nLista dostępnych komend - wpisz pomoc. Dla administratora - adm pomoc." % (msgact, uin, texto) )
    return
  elif text[0:1] == '"' or text[0:1] == "'" :
    ekg.command("%s %d Komendy powinny być pisane bez cudzysłowów :).%s" % (msgact, uin, helpshort) )
    return
  else:
    ekg.command("%s %d '%s' - zła komenda.%s" % (msgact, uin, texto, helpshort) )