# -*- coding: utf-8 -*-


import api

from utils import Armee

SCHEMA = ((1,0), (1,1), (1,2), (2,2), (3,1), (3,2), (3,3), (5,0), (6,0),
          (7,0), (7,1), (5,2), (5,3), (6,3), (7,3))

class Bataillon():
    def __init__(self, n, cible, armee):
        self.n = n
        self.effectif = 0
        self.cible = cible
        self.pos = None
        self.armee = armee

    def fixe_cible(self, cible):
        self.cible = cible
        self.armee.bataillons_a_deplacer.append(self)

    def creer(self):
        if self.effectif < self.n:
            n = min(self.n - self.effectif, moi.magie()//api.COUT_SORCIER)
            moi.creer(n)
            self.effectif += n
        else:
            self.pos = (0,0)
            self.armee.bataillon_cree(self)


    def deplacer(self):
        self.n = min(self.n, moi.nb_sorciers(self.pos))
        arrivee = prochaine_etape(self.pos, self.cible)
        err = moi.deplacer(self.pos, arrivee, self.n)
        print(err)
        self.pos = arrivee
        if self.pos == self.cible:
            self.armee.bataillon_arrive(self)

class Armee():
    def __init__(self):
        self.bataillons = []
        self.bataillons_a_creer = []
        self.bataillons_a_deplacer = []


    def update_construction(self):
        for bat in self.bataillons_a_creer:
            bat.creer()

    def update_deplacement(self):
        for bat in self.bataillons_a_deplacer:
            bat.deplacer()

    def bataillon_arrive(self, bat):
        self.bataillons_a_deplacer.remove(bat)

    def bataillon_cree(self, bat):
        self.bataillons_a_creer.remove(bat)
        self.bataillons_a_deplacer.append(bat)

    def add(self, n, cible):
        bat = Bataillon(n, cible, self)
        self.bataillons.append(bat)
        self.bataillons_a_creer.append(bat)

armee = Armee()

def partie_debut():
    pass

def phase_construction():
    tour = api.tour_actuel()
    if tour == 1:
        for t in SCHEMA:
            armee.add(1, t)
    elif tour > 10:
        for t in armee.bataillons:
            if tour % 4 == 2:
                t.fixe_cible((t.cible[0]+1, t.cible[1]))
            elif tour % 4 == 3:
                t.fixe_cible((t.cible[0], t.cible[1]+1))
            elif tour % 4 == 0:
                t.fixe_cible((t.cible[0]-1, t.cible[1]))
            elif tour % 4 == 1:
                t.fixe_cible((t.cible[0], t.cible[1]-1))
    armee.update_construction()

def phase_deplacement():
    armee.update_deplacement()

def phase_tirs():
    pass

def phase_siege():
    pass

def partie_fin():
    pass