#!/usr/bin/python
#
# Made by Calatraba Mickael
# For THE Jam-bom Beurre-man
# Epitech login calatr_m
# Mickael.calatraba@epitech.eu
# Version: Beta 1.0
#

from sys import argv
import sys
import os
                                                             
#CLASS__________

class Map:
    def setData(self, more):
        self.data = self.data + more
    def setName(self, name):
        self.name = name
        self.outName = "".join("./data/maps/" + "".join(name.split("/")[len(name.split("/"))-1] + ".xml"))
    def writeFile(self):
        self.outFd.write(self.data)
    def enumType(self, c):
        if (c == "1"):
            return (self.type1)
        else:
            return (self.type2)

    def __init__(self):
        self.header = "<?xml version=\"1.0\"?>\n<map x=\""
        self.caseX = "\t<case x=\""
        self.caseY = "\" y=\""
        self.endLine = "\">\n"
        self.type1 = "type=\"1\"/>\n"
        self.type2 = "type=\"2\"/>\n"
        self.end = "</map>\n"
        self.name = ""
        self.outName = ""
        self.fd = 0
        self.outFd = 0
        self.data = ""
        self.x = 0
        self.y = 0
#_____________________


def     parseFile(Map):
    files = Map.fd.readlines()
    key = 0
    y = 0
    x = 0
    for line in files:
        x = 0
        if (line.find(":") != -1):
            if key == 0:
                Map.x = line[2:len(line) - 1]
                Map.setData(Map.x)
                Map.setData(Map.caseY)
                key = key + 1
            else:
                Map.y = line[2:len(line) - 1]
                Map.setData(Map.y)
                Map.setData(Map.endLine)
        elif (line[0] != "\n"):
            for c in line:
                if (c != "0" and c != "\n"):
                    Map.setData(Map.caseX)
                    Map.setData(str(x))
                    Map.setData(Map.caseY)
                    Map.setData(str(y))
                    Map.setData("\" ")
                    Map.setData(Map.enumType(c))
                    x = x + 1
                elif (c != "\n"):
                    x = x + 1
            y = y + 1
    Map.setData(Map.end)

if __name__ == '__main__':
    try:
        if (len(argv) != 2):
            raise ValueError
        Map = Map()
        Map.setName("".join("./data/map_generator/model_map/" + argv[1].split('/')[len(argv[1].split('/')) - 1]))
        Map.data = Map.header
        try:
            with open(Map.name, "r") as Map.fd:
                parseFile(Map)
            try:
                with open(Map.outName, "w") as Map.outFd:
                    Map.outFd.write(Map.data)
                os.remove(Map.name)
            except EnvironmentError:
                print "Serious error when writing."
        except EnvironmentError:
            print "Serious error when reading."
    except ValueError:
        print "Warning in map."
