# coding: cp1251
import time
from math import sqrt
import random
from datetime import datetime, timedelta
from multiprocessing import Process

from configparser import ConfigParser

from api import TravianApi
from notifier.telegram import Telegram


def printl(*args):
    print(datetime.now().strftime('%d.%m.%Y %H:%M:%S'), ' | ', *args)


def pause(_min, _max):
    time.sleep(random.randint(_min, _max) * 60)


def adaptive_pause():
    now = datetime.now()

    night = (datetime(now.year, now.month, now.day, 0, 0), datetime(now.year, now.month, now.day, 8, 59, 59))
    day = (datetime(now.year, now.month, now.day, 9, 0), datetime(now.year, now.month, now.day, 23, 59, 59))

    if night[0] < now < night[1]:
        sl = random.randint(55, 123)
        printl('Следующая проверка через: ', sl, 'мин.')
        time.sleep(sl * 60)
    elif day[0] < now < day[1]:
        sl = random.randint(12, 18)
        printl('Следующая проверка через: ', sl, 'мин.')
        time.sleep(sl * 60)


class TravianBot:
    settings = ConfigParser()
    settings.read('config/config.ini')

    api = TravianApi(
        domain=settings.get('connection', 'domain'),
        server=settings.get('connection', 'server'),
        user=settings.get('connection', 'username'),
        password=settings.get('connection', 'password')
    )

    api.login()

    def __init__(self):
        self.telegram = Telegram(self.settings)

        self.farm_list = list({
            (155, 37), (149, 40), (156, 47), (158, 47), (156, 22), (158, 19), (162, 45)
        })

        self.farm_list_spam = list({
            (154, 23), (158, 31), (160, 20), (161, 34),
            (167, 26), (164, 19), (147, 32),
            (149, 17), (151, 15), (144, 24), (144, 27),
            (153, 19), (162, 35), (170, 25), (170, 23),
            (168, 18), (146, 31), (159, 25), (155, 28)
        })

        self.min_troops_speed = 1 / 257  # fields per second

        self.farm_troops = {'Ополченцы': 't1', 'Колесницы Решефа': 't6',
                            'Стражники Анхура': 't5', 'Воины с хопешем': 't3'}

    def _get_distance(self, coords_1, coords_2):
        return round(sqrt((coords_1[0] - coords_2[0])**2 + (coords_1[1] - coords_2[1])**2), 1)

    def get_attacks(self):
        movs = self.api.get_movements()

        if movs['income']:
            for m in movs['income']:
                if 'ападени' in m:
                    return m + ': ' + movs['income'][m]
        return ''

    def _shake_list(self, l):
        list_length = len(l)

        for i in range(list_length):
            random_index = random.randint(0, list_length - 1)
            l[i], l[random_index] = l[random_index], l[i]

        return l

    def _farm(self, available_troops, farm_list):
        _t = []
        for coords in self._shake_list(farm_list):

            _a = {}
            for t in available_troops:
                n = int(available_troops[t]) // len(farm_list)
                _a[t] = n

            distance = self._get_distance(self.main_village, coords)
            troops_time = round(distance * 181)

            if not self.api.send_attack(coords, **_a):
                printl(coords, 'отправлено: %s' % _a)
                _t.append(troops_time)
            else:
                printl('Ошибка при отправке набега на деревню {}.'.format(coords))

            time.sleep(random.randint(4, 9))

        return max(_t)

    def run(self):
        n = 5

        while True:
            try:
                prev = datetime.now()

                self.api.set_village(13330)
                self.api.create_units(solar_id=34, t6=n)

                self.api.set_village(16537)
                self.api.create_units(solar_id=32, t5=n)

                adaptive_pause()
                now = datetime.now()
                n = (now - prev).total_seconds() // 60 // 12
            except KeyboardInterrupt:
                exit(0)
            except:
                time.sleep(120)
                self.api.login()


if __name__ == '__main__':
    bot = TravianBot()
    bot.run()
