class Bot < ActiveRecord::Base
  belongs_to :user
  belongs_to :profile, optional: true
  serialize :telegram_subscriber_ids, Array
  has_and_belongs_to_many :commands

  # def send_text
  #   if self.telegram_api_token
  #     Telegram::Bot::Client.run(telegram_api_token) do |bot|
  #       bot.api.send_message(chat_id: message.chat.id, text: response_text, parse_mode: "Markdown")
  #     end
  #   end
  # end

  def fortune
    `fortune -a`
  end

  def telegram_listen
    # `echo "#{Time.now} hi from telegram listen" > tglisten.txt`
    return unless self.telegram_api_token
    bot = Telegram::Bot::Client.new(telegram_api_token)
    # Signal.trap('INT') do
    #   bot.stop
    # end
    bot.listen do |message|
      # TODO Logging
      # File.open("./logs/#{@botname}.log", 'a') { |f| f.write(["\n", Time.now, message.chat.id, message.from.id, message.from.first_name, message].join("\t")) }
      case message
      when Telegram::Bot::Types::Message
        # Debugging use next to skip/drop the queue
        # next
        # eval(IO.read('./app/models/commands/fortune.rb'), binding)
        case message.text
          when /^\/fortune/i
          response_text = `fortune`
          begin
            bot.api.send_message(chat_id: message.chat.id, reply_to_message_id: message.message_id, text: response_text, parse_mode: "Markdown")
          rescue
            puts "Error from fortune"
          end
        end
        case message.text
        when /^\/subscribe/i, /^\/sub/i, /^\/start/i
          response_text = `fortune -a`
          if self.telegram_subscriber_ids.include? message.chat.id
            response_text = "You remain subscribed to #{bot.api.call("getMe")["result"]["first_name"]}\n\n" + response_text
          else
            self.telegram_subscriber_ids << message.chat.id
            self.save
            response_text = "Now subscribed to #{bot.api.call("getMe")["result"]["first_name"]}\n\n" + response_text
          end
          begin
            bot.api.send_message(chat_id: message.chat.id, reply_to_message_id: message.message_id, text: response_text, parse_mode: "Markdown")
          rescue
            puts "Error from subscribe / start"
          end
        end
        case message.text
        when /^\/stop/i, /^\/unsub/i,/^\/unsubscribe/i
          response_text = `fortune -a`
          if self.telegram_subscriber_ids.include? message.chat.id
            self.telegram_subscriber_ids.delete message.chat.id
            self.save
            response_text = "You are now unsubscribed from #{bot.api.call("getMe")["result"]["first_name"]}\n\n" + response_text
          else
            response_text = "You remain unsubscribed to #{bot.api.call("getMe")["result"]["first_name"]}\n\n" + response_text
          end
          begin
            bot.api.send_message(chat_id: message.chat.id, reply_to_message_id: message.message_id, text: response_text, parse_mode: "Markdown")
          rescue
            puts "Error from start"
          end
        end
        case message.text
        when /^\/wallet/i, '/mywallet'
          # mywallet(message.from.id, bot, message)
          # unless get_wallet(message.from.id)
          #   create_wallet(message.from.id, bot, message)
          # end
          telegram_wallet = get_or_create_telegram_wallet(message.from.id)
response_text = "Hello #{message.from.first_name}
ICP Account Id:
```
#{telegram_wallet.get_icp_id}
```
ICP Principal:
```
#{telegram_wallet.get_icp_principal}
```
"
          begin
            bot.api.send_message(chat_id: message.chat.id, reply_to_message_id: message.message_id, text: response_text, parse_mode: "Markdown")
          rescue
            puts "Error from mywallet"
          end

        end
      end
    end
  end

  def get_or_create_telegram_wallet(telegram_id)
    telegram_wallet = TelegramWallet.where(telegram_id: telegram_id).first_or_initialize
    telegram_wallet.save
    return telegram_wallet
  end

end
